我想用 do 创建选项,而用户在输入正确的字母后将跳出循环。我尝试制作一个,但如果我输入 while(type == "Y") 它只会让我脱离循环,无论我按什么或如果我退出 while(type != "Y") 它都会发生永远循环,所以我在其他地方做错了,但我不知道在哪里。
public class JavaApplication8 {
static String type;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Press Y to get out of the loop");
type = scanner.next();
} while (type == "Y");
}
}
最佳答案
而不是
while (type == "Y");
使用
while (type.equals("Y"));
==
检查两个字符串是否引用同一个对象
.equals()
检查两个对象包含相同的数据。
另外,似乎您希望只要用户不输入Y
就运行循环。因此将其更改为:
while (!type.equals("Y"));
关于java - 使用输入扫描器执行 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469960/