计算行程距离的非常简单的程序(一周前刚刚开始),我有这个循环用于解决真或假问题,但我希望它适用于简单的"is"或“否”。我为此分配的字符串是答案。
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"
进行比较code> (大概是不区分大小写的方式)。请注意,again
的声明需要从 boolean
更改为 String
。
String again = null;
do {
... // Your loop
again = input.nextLine(); // This consumes the \n at the end
} while ("yes".equalsIgnoreCase(again));
关于java - 尝试使用等于 "yes"或 "no"的字符串变量重新启动 do-while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20915880/