尝试使用String变量重新启动do-while循环,使其等于“yes”或“no”

非常简单的程序计算旅行距离(刚开始一周前),我有这个循环工作的真假问题,但我希望它适用于简单的“是”或“否”。 我为此分配的字符串是答案。

public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); double distance; double speed; boolean again = true; String answer; do{ System.out.print("Tell me your distance in miles: "); distance = input.nextDouble(); System.out.print("Tell me your speed in which you will travel: "); speed = input.nextDouble(); double average = distance / speed; System.out.print("Your estimated time to your destination will be: " + average + " hours\n\n"); if(average < 1){ average = average * 10; System.out.println(" or " + average + " hours\n\n"); } System.out.println("Another? "); again = input.nextBoolean(); }while(again); } } 

您需要使用input.next()而不是input.nextBoolean() ,并将结果与​​字符串文字"yes" (可能是以不区分大小写的方式)。 请注意,声明again需要从boolean更改为String

 String again = null; do { ... // Your loop again = input.nextLine(); // This consumes the \n at the end } while ("yes".equalsIgnoreCase(again)); 

做就是了

  answer = input.nextLine(); } while(answer.equals("yes")); 

您可能想要考虑更灵活。 例如:

 while (answer.startsWith("Y") || answer.startsWith("y")); 
 String answer=null; do{ //code here System.out.print("Answer? (yes/no) :: "); answer=input.next(); }while(answer.equalsIgnoreCase("yes")); 

如果用户输入“是”,上述条件会使“while”循环运行,如果他输入除yes之外的任何内容,则会终止。