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);
}
}
the above condition makes " while" loop run if user enter's yes and will terminate if he enters anything except yes.
just do
You might want to consider being more flexible though. For example:
You need to use
input.next()
instead ofinput.nextBoolean()
, and compare the result to a string literal"yes"
(presumably, in a case-insensitive way). Note that the declaration ofagain
needs to change fromboolean
toString
.