Repeat the temperature programming project adding a loop that allows the user to continue entering in temperatures, until they enter a Q or q to exit that portion of the program. The user should enter a Q or q to exit and an empty String to continue. (Any other entry should cause the question to be repeated) If the user enters a different letter that F or C(either upper or lower case) for the temperature, print an error message and ask the user to enter the correct temperature scale without asking for a new numeric value.
这是我到目前为止所拥有的......我无法让它读取他们是否输入了 65D 而不是 65C。如果他们输入 D 而不是 F/f 或 C/c,我不知道如何在代码中循环它...
import java.util.Scanner;
public class AssignmentFour {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the temperature you want converted.");
System.out.println("Followed by: 'C/c' or 'F/f'");
String input2 = keyboard.next();
do{
String temp = input2.trim();
String degreesAsString = temp.substring(0, temp.length()-1);
double degrees = Double.parseDouble(degreesAsString);
if(temp.endsWith("C") || temp.endsWith("c")){
double degreeF = 9 * degrees / 5 + 32;
System.out.println(input2 + " is equal to: ");
System.out.printf("%.2f", degreeF);
System.out.println(" Fahrenheit.");
} else if(temp.endsWith("F") || temp.endsWith("f")){
double degreeC = 5 * (degrees - 32) / 9;
System.out.println(input2 +" is equal to: ");
System.out.printf("%.2f", degreeC);
System.out.println(" Celsius.");
} else if (temp.endsWith(""));{
System.out.println("ERROR: Please enter either 'F/f or C/c'.");
}
break;
} while(!input2.equals(""));
System.out.println("");
}
最佳答案
只需将 ... = Keyboard.next()
移动到 do-while 循环内即可在循环时读取新的用户输入。此外,您应该删除 break ;
语句当前只是阻止执行任何循环。
关于java - 用户输入温度不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30540025/