Java 用户输入必须在范围内/为 20 行生成 10 的整数

标签 java loops boolean conditional-statements

我的代码中需要一些东西。我已经看了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/

相关文章:

java - JAXB 将 boolean 值编码为复杂类型

java - servlet 的数据库连接问题 - Java webapp

Java try/catch block 在捕获异常时不输出文本

php - 循环内循环达到内存限制

c - 为什么 while 循环对于这个链接列表程序不起作用?

c++ - 使用带有 bitset 的 initializer_list

java - 基本的银行程序无限地执行 do 循环。我究竟做错了什么?

java - 如何防止SIGINT信号杀死Java中的子进程

java - While 循环 JOptionPane 问题

c++ - C++ 中逻辑 "or"对 bool 值的效率