简体   繁体   English

尝试使用等于“是”或“否”的String变量重新启动do-while循环

[英]Trying to restart a do-while loop with a String variable to equal “yes” or “no”

Very simple program calculating travel distance(just started a week ago) and I have this loop working for a true or false question, but I want it to work for a simple "yes" or "no" instead. 计算行程距离的非常简单的程序(一周前才开始),并且我使此循环适用于是非题,但我希望它适用于简单的“是”或“否”。 The String I have assigned for this is answer. 我为此分配的字符串是答案。

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);

}

}

You need to use input.next() instead of input.nextBoolean() , and compare the result to a string literal "yes" (presumably, in a case-insensitive way). 您需要使用input.next()而不是input.nextBoolean() ,然后将结果与字符串文字"yes" (大概是不区分大小写的方式)。 Note that the declaration of again needs to change from boolean to String . 注意, again声明需要从boolean更改为String

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

just do 做就是了

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

You might want to consider being more flexible though. 您可能需要考虑更加灵活。 For example: 例如:

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"));

the above condition makes " while" loop run if user enter's yes and will terminate if he enters anything except yes. 如果用户输入“是”,则上述条件使“ while”循环运行,如果输入“是”,则终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM