一个非常简单的计算行进距离的程序(一周前才开始),我使这个循环适用于是非题,但我希望它适用于简单的“是”或“否”。我为此分配的字符串是答案。
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));