所以我几乎是一个编码新手,正忙着玩“do while 循环”,我的代码可能很糟糕,而且很可能有 1000 种更好的方法来完成我想做的事情,但无论如何。
我尝试使用 main 方法,然后使用其他两种方法(用于练习目的)来要求用户选择 1 到 10 之间的数字,然后再尝试一次。
我让代码运行,直到它要求用户输入是/否,但随后代码停止运行,我不明白为什么?
public static void main(String[] args) {
chooseNum();
}
public static boolean chooseNum() {
int number = 4;
do {
System.out.println("Enter a number 1 to 10");
int userNum = in.nextInt();
if (number == userNum) {
System.out.println("You chose the correct number!");
return tryAgain();
} else if (number != userNum) {
System.out.println("You chose the incorrect number!");
return tryAgain();
} else
System.out.println("invalid Response");
}
while (false);
return false;
}
public static boolean tryAgain(){
System.out.println("Try again? yes/no");
String response = in.nextLine();
if (response.equalsIgnoreCase("yes")){
return chooseNum();
}else if (response.equalsIgnoreCase("no")){
return false;
}else
return false;
}
}
我的输出如下:
Enter a number 1 to 10
1
You chose the incorrect number!
Try again? yes/no
Process finished with exit code 0
我似乎无法进一步输入是或否。
我知道这是基本的,我很可能看起来很可怜,但任何帮助将不胜感激。
也许另一个新手可以有机会帮助别人:)
非常感谢!
最佳答案
使用 next()
而不是 nextLine()
因为当您读取 int 并添加 \n
来提交值时。扫描仪将此视为输入。 next()
应该忽略之前输入的 \n
并按照您的预期接受输入。
关于java - Java 中的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44661797/