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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.