Java 用户输入必须在范围内/生成 20 行乘以 10 的整数
Java user input has to be in range / Produce integers by 10 for 20 lines
我的代码中需要一些东西。我已经连续看了 8 个小时,还是想不通。我需要用户输入介于 -459 和 212 之间。如果它是一个超出范围的整数,它将打印行以重新输入它然后继续并转换它们。现在它没有做任何一个,只是通过代码。我应该使用布尔值还是 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
块中。如果你想让它重复直到你得到一个有效的输入,你需要把它变成一个 while
循环:
while(Fahrenheit < -459 || Fahrenheit > 212) {
System.out.println("Please enter a number between -459 and 212 degrees:");
Fahrenheit = scan.nextInt();
}
第二个问题我没看懂
我的代码中需要一些东西。我已经连续看了 8 个小时,还是想不通。我需要用户输入介于 -459 和 212 之间。如果它是一个超出范围的整数,它将打印行以重新输入它然后继续并转换它们。现在它没有做任何一个,只是通过代码。我应该使用布尔值还是 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
块中。如果你想让它重复直到你得到一个有效的输入,你需要把它变成一个 while
循环:
while(Fahrenheit < -459 || Fahrenheit > 212) {
System.out.println("Please enter a number between -459 and 212 degrees:");
Fahrenheit = scan.nextInt();
}
第二个问题我没看懂