我需要修改我的程序,以便在需要时可以多次运行它。如果用户输入 Q 或 q,并且输入除请求的条目(或退出命令)以外的任何内容,我需要退出程序,问题将重复。 这是我到目前为止的代码:
import java.util.Scanner;
public class TemperatureLoop
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Enter a temperature in degrees (for example 32.6): ");
double temp;
temp = keyboard.nextDouble();
System.out.println("Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius: ");
String letter = keyboard.next();
double total = 0;
//if Farenheit then do this equation
if (letter.equals("F") || (letter.equals("f")))
{
total = ((temp-32)*5)/9; //convert the entered temperature to Celsius
System.out.println(temp + " degrees F = " + total + " degrees Celsius");
}
else //if Celsius then do this
if (letter.equals("C") || (letter.equals("c")) )
{
total = (((temp*9))/5)+32; //convert the entered temperature to Farenheit
System.out.println(temp + " degrees C = " + total + " degrees Fahrenheit");
}
}
}
最佳答案
我建议将您所拥有的内容放入 while 循环中,如果用户输入“Q”或“q”,该循环就会中断。类似于下面的内容:
// Declare your breaking condition variable outside the while loop
boolean done = false;
while (!done){
// Your existing code here
// A conditional to check for 'Q' or 'q'
// set done to true if the above line evaluates as true.
}
关于java - 向现有的 java 程序添加循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172325/