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。是的,解决了我的问题,我会接受你的答案,非常感谢