[英]How to prompt user for input again using do-while loops
I am trying to prompt the user if she wants to do a conversion again. 我正在尝试提示用户是否要再次进行转换。 I am using a do while loop statement and this is the code.
我正在使用do while循环语句,这是代码。
import java.util.Scanner;
public class FinalTemp {
public static void main(String[] args) {
//Declare the variables
float temperature = 0;
boolean number;
//The condition is check before running
do {
System.out.println("Enter Farenheit number:");
Scanner input = new Scanner(System.in);
if (input.hasNextFloat())
{
temperature = input.nextFloat();
number = true;
temperature = ((temperature - 32)*5)/9;
}
else
{
System.out.println("Invalid input");
number = false;
input.next();
}
} while (!(number));//means not equal to the variable number
System.out.println("Celcius is " + temperature);
Your code ends in the middle so it is not clear where exactly you have you problems. 您的代码在中间结束,因此不清楚您到底在哪里遇到问题。 Would something like following work for you?
像下面这样的事情对您有用吗?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean stop = false;
// outer loop for two questions
do {
//Declare the variables
float temperature = 0;
boolean number;
// The loop for conversion question
//The condition is check before running
do {
System.out.println("Enter Farenheit number:");
if (input.hasNextFloat()) {
temperature = input.nextFloat();
number = true;
temperature = ((temperature - 32) * 5) / 9;
} else {
System.out.println("Invalid input");
number = false;
input.next();
}
} while (!(number));//means not equal to the variable number
System.out.println("Celcius is " + temperature);
// The loop for "one more?"
do {
System.out.println("Do you want to convert one more? (Y/N)");
String yesNo = input.next();
boolean yes = yesNo.toLowerCase().charAt(0) == 'y';
boolean no = yesNo.toLowerCase().charAt(0) == 'n';
if (yes) {
stop = false;
break;
} else if (no) {
stop = true;
break;
} else
System.out.println("Only Y or N is expected.");
}
while (true);
}
while (!stop);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.