Trying to restart a do-while loop with a String va

2020-05-02 11:35发布

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

}

}

标签: java
3条回答
萌系小妹纸
2楼-- · 2020-05-02 11:53
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.

查看更多
手持菜刀,她持情操
3楼-- · 2020-05-02 12:02

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"));
查看更多
够拽才男人
4楼-- · 2020-05-02 12:13

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). Note that the declaration of again needs to change from boolean to String.

String again = null;
do {
    ... // Your loop
    again = input.nextLine(); // This consumes the \n at the end
} while ("yes".equalsIgnoreCase(again));
查看更多
登录 后发表回答