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

时间:2014-01-04 01:56:27

标签: java

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

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

}

}

3 个答案:

答案 0 :(得分:2)

您需要使用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));

答案 1 :(得分:1)

只是做

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

您可能希望考虑更灵活。例如:

while (answer.startsWith("Y") || answer.startsWith("y"));

答案 2 :(得分:0)

String answer=null;

    do{

       //code here
      System.out.print("Answer? (yes/no) :: ");
      answer=input.next();

      }while(answer.equalsIgnoreCase("yes"));

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