我的代码中需要一些东西。我已经看了8个小时了,还是没明白。我需要用户输入介于 -459 和 212 之间。如果它是超出范围的整数,它将打印行以重新输入它,然后继续进行转换。现在它没有做任何一个,只是浏览代码。我应该使用 boolean 值还是 if ?不知道。
第二个问题是当华氏温度和摄氏温度在转换后打印出来时,我需要它们再列出 20 行,每个温度加 10。这是计数吗?请提供主要帮助!
到目前为止我所拥有的:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Temperatures {
public static void main(String[] args) {
double Fahrenheit;
double Celsius;
Scanner scan = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit: ");
Fahrenheit = scan.nextInt();
if(Fahrenheit >= -459 && Fahrenheit <= 212)
System.out.println("Please enter a number between -459 and 212 degrees:");
Fahrenheit = scan.nextInt();
Celsius = ((Fahrenheit -32)*5)/9;
DecimalFormat fmt = new DecimalFormat("#.##");
System.out.print("Fahrenheit: " + Fahrenheit + " Celsius: " + fmt.format(Celsius));
}
}
最佳答案
你的if
条件被颠倒了。并且下一个 nextInt()
不在 if
block 中。如果您希望它重复直到获得有效输入,您需要将其变成 while
循环:
while(Fahrenheit < -459 || Fahrenheit > 212) {
System.out.println("Please enter a number between -459 and 212 degrees:");
Fahrenheit = scan.nextInt();
}
我不太明白第二个问题。
关于Java 用户输入必须在范围内/为 20 行生成 10 的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41882540/