Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 猜一个数字的程序_Java_While Loop - Fatal编程技术网

Java 猜一个数字的程序

Java 猜一个数字的程序,java,while-loop,Java,While Loop,嗨,伙计们,我正在写一个程序,与用户玩猜谜游戏。你需要想出一个数字,程序就会猜出来。这是我的密码: public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Guess a number between 1 do 100 and i'll guess it"); int min = 0; i

嗨,伙计们,我正在写一个程序,与用户玩猜谜游戏。你需要想出一个数字,程序就会猜出来。这是我的密码:

 public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Guess a number between 1 do 100 and i'll guess it");
        int min = 0;
        int max = 100;
        int guess = (max-min)/2 + min;
        boolean end = false;
        while(!end){

            System.out.println("zgaduje " + guess);
            String userInput = scan.next();
            if(userInput.equalsIgnoreCase("too much")){
                max = guess;
            }
            else if(userInput.equalsIgnoreCase("too small")){
                min=guess;
            }
            else if(userInput.equalsIgnoreCase("correct")){
                end = true;
            }
             guess = (max-min)/2 + min;
        }
    }
}
因此程序猜测一个数字,然后根据用户输入(太小或太多)再次猜测。它并没有按预期的那样工作,它只会反复显示最初的猜测。您知道这里可能有什么问题吗?

您使用
scan.next()。对于输入的
太多
,将只返回
太多


要阅读整行,需要使用
scan.nextLine()

您应该使用下一行而不是下一行:

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Guess a number between 1 do 100 and i'll guess it");
        int min = 0;
        int max = 100;
        int guess = (max-min)/2 + min;
        boolean end = false;
        while(!end){

            System.out.println("guess is" + guess);
            String userInput = scan.nextLine();
            if(userInput.equalsIgnoreCase("too much")){
                max = guess;
            }
            else if(userInput.equalsIgnoreCase("too small")){
                min=guess;
            }
            else if(userInput.equalsIgnoreCase("correct")){
                end = true;
            }
             guess = (max-min)/2 + min;
        }
    }

@阿诺:我想他们不是在问数字。他们会说“想一个数字”。然后打印一个数字,并询问用户是否猜对了。“猜一个介于1到100之间的数字,我会猜出来”然后min必须是1,而不是0。是的,解决了我的问题,我会接受你的答案,非常感谢