Why does this do-while loop not produce the right output?

痞子三分冷 提交于 2019-12-02 13:17:39

System.in.read(); gives you char. so when you enter "1", it gives you its char value, 49. so you can not enter integer 5 with typing numbers. so change your reading method. you can use Scanner

You are doing the opposite - an answer less than 5 is accepted as correct.

Here is a working version of your code.

As mentioned in previous answers, the System.in reads in characters so you cannot read in numbers directly. Below The code is leveraging the BufferedReader API whitch works on an InputStream.

public class App {


        public static void main(String[] args) throws IOException {

                System.out.println("Hello, come and play a game with me!");

                int x = 5;
                int guess;

                do                
                {               
                    System.out.println("Please input a number...");
                   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

                   guess = Integer.parseInt(br.readLine());
                    if(guess < 5){

                        System.out.println("You guessed the number!");                    
                        break;                    
                    }

                } while(guess>5);        
         }    
    }

it looks like you did not use the variable x, try using the Scanner class to get input from the user

public static void main(String[] args) throws IOException {

System.out.println("Hello, come and play a game with me!");
 int guess;
 Scanner input = new Scanner(System.in);



do {
    System.out.println("Please input a number...");
     guess = input.nextInt();
           if (guess < 5) {
        System.out.println("You guessed the number!");
        break;
    }
} while (guess > 5);

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!