【发布时间】:2013-09-08 12:57:49
【问题描述】:
我正在尝试做一个 while 循环,如果密码正确则打印欢迎语句,如果密码错误则拒绝您。当你错了,我希望它重新提出问题。不幸的是,当密码错误时,它只会发送垃圾邮件并且不会重新循环。谢谢!
import java.util.Scanner;
public class Review {
public static void main(String[] args) {
Scanner userInput = new Scanner(System. in );
System.out.println("Enter user password");
String userGuess = userInput.nextLine();
int x = 10;
while (x == 10) {
if (userGuess.equals("test")) {
System.out.println("Welcome");
return;
} else if (!userGuess.equals("test")) {
System.out.println("Wrong, try again");
break;
}
}
}
}
【问题讨论】:
-
从
else if中删除break。并将else if替换为else。 -
else if (!userGuess.equals("test"))那时你已经知道userGuess != "test",所以只需使用else -
好的,我做到了。程序仍然会在 else 语句中发送垃圾邮件
-
已修复。刚刚添加了“userGuess = userInput.nextLine();”在 else 语句中
-
这可能不是正确的解决方法。
标签: java string loops while-loop comparison