尝试使用String变量重新启动do-while循环以等于“yes”或“不” [英] Trying to restart a do-while loop with a String variable to equal "yes" or "no"
本文介绍了尝试使用String变量重新启动do-while循环以等于“yes”或“不”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
非常简单的程序计算行程距离(刚开始一周前),我有这个循环工作的真假问题,但我希望它适用于简单的是或否。我为此分配的字符串是答案。
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);
}
}
推荐答案
你需要使用 input.next()
而不是 input.nextBoolean()
,并将结果与字符串文字是
进行比较(可能是以不区分大小写的方式)。请注意,再次声明
需要从布尔
更改为 String
。
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));
这篇关于尝试使用String变量重新启动do-while循环以等于“yes”或“不”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文