Java中的While循环问题

Java中的While循环问题,java,Java,这是我的一点代码 System.out.print("Would you like to continue (Y/N)?"); while (!Anwser.equals("Y")){ Anwser = UserInput.next(); System.out.println("Would you like to continue (Y/N)?"); } 这就是答案 > Would you like to continue (Y/N)? > Would you l

这是我的一点代码

System.out.print("Would you like to continue (Y/N)?");
while (!Anwser.equals("Y")){
    Anwser = UserInput.next();
    System.out.println("Would you like to continue (Y/N)?");
}
这就是答案

> Would you like to continue (Y/N)? 
> Would you like to continue (Y/N)?
虽然我输入了Y,但条件不满足,为什么它会再次打印出来?在此之后,它继续执行代码:

while循环执行零次或多次

do while循环执行一次或多次

对于延续性问题,您并不真正关心用户输入的内容,只要是“Y”或“Y”。 其他任何操作都将终止该程序。 还有一个延续问题,程序通常希望运行一次。因此,将代码包装在do-while循环中


至于为什么你的代码不起作用。也许您应该在循环开始之前指定一个值来回答。

尝试更改一个WSER变量的值,并用用户的输入替换它

像这样:

System.out.print("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
while (!Anwser.equals("Y")){
    System.out.println("Would you like to continue (Y/N)?");
    Anwser = UserInput.next();
}

之所以要打印两次,是因为第一行在循环外打印问题,然后测试未捕获的答案,然后依赖于引用变量初始化的内容,然后进入while循环,while循环首先获取用户对最后一个问题的输入,然后再次打印问题

System.out.print("Would you like to continue (Y/N)?"); //prints to screen
//no input captured before test
while (!Anwser.equals("Y")){ //tests the reference variable
   Anwser = UserInput.next(); //captures user input after test
   System.out.println("Would you like to continue (Y/N)?"); //asks question again
   }
while循环是一个预测试循环,这意味着它在运行内部代码之前测试条件。使用这段代码,您将测试对第一个问题的响应,以回答第二个问题。所以,如果你想保持while循环,你真正需要做的就是把问题放在循环中,就像这样:

while (!Anwser.equalsIgnoreCase("Y"))
{    
   System.out.println("Would you like to continue (Y/N)?");
   Anwser = UserInput.next();
}
另外,因为您只是捕获一个字符,所以可以尝试使用char变量,而不是使用String对象来保存字符文本。这就是解决方案:

char answer = ' ';    
Scanner userInput = new Scanner(System.in);

while (answer != 'N') // check for N to end
{           
   System.out.println("Would you like to continue (Y/N)?");
   answer = Character.toUpperCase(userInput.nextLine().charAt(0));
}
char answer = ' ';    
Scanner userInput = new Scanner(System.in);

while (answer != 'N') // check for N to end
{           
   System.out.println("Would you like to continue (Y/N)?");
   answer = Character.toUpperCase(userInput.nextLine().charAt(0));
}