java - 在简单的 Java 程序上处理键盘输入

标签 java input

我编写了一个 java 程序,允许人们将 Fahrenheit 转换为 Celsius 或将 Celsius 转换为 Fahrenheit。现在代码运行良好,但如果我删除两个 if 语句 中的两个代码 input=keyboardnextLine(),代码只运行一次并停止。

我不知道我哪里做错了。我认为 if 语句 中的两个 input=keyboardnextLine() 没有用。请帮助我,这让我很困惑!

import java.util.Scanner;

public class Q2  {
    public static void main(String[] args) {
        System.out.println("Enter\"f\" or \"F\" to convert fahrenheit to centigrade");
        System.out.println("Enter\"c\" or \"C\" to convert centigrade to fahrenheit");
        System.out.println("Enter someting else to quit");
        Scanner keyboard = new Scanner (System.in);
        String input = keyboard.nextLine();
        double fah, cel;
        while ((input.equalsIgnoreCase("f")) || (input.equalsIgnoreCase("c"))) {
            if (input.equalsIgnoreCase("f")) {
                System.out.println("Enter the temperature in fahrenheit. I will tell you the centigrade.");
                fah = keyboard.nextDouble();
                cel = 5*(fah - 32) / 9;
                System.out.println(fah+ " in centigrade is " + cel + " in fahrenheit.");
                System.out.println(" ");
                System.out.println("Enter\"f\" or \"F\" to convert fahrenheit to centigrade");
                System.out.println("Enter\"c\" or \"C\" to convert centigrade to fahrenheit");
                System.out.println("Enter someting else to quit");
                input = keyboard.nextLine();
            }

            if (input.equalsIgnoreCase("c")) {
                System.out.println("Enter the temperature in centigrade. I will tell you the fahrenheit.");
                cel = keyboard.nextDouble();
                fah = 9 * cel / 5 + 32;
                System.out.println(cel + " in centigrade is " + fah + " in fahrenheit.");
                System.out.println(" ");
                System.out.println("Enter\"f\" or \"F\" to convert fahrenheit to centigrade");
                System.out.println("Enter\"c\" or \"C\" to convert centigrade to fahrenheit");
                System.out.println("Enter someting else to quit");
                input = keyboard.nextLine();
            }
            input = keyboard.nextLine();
        }
        System.exit(0);
    }
}

最佳答案

您的代码从读取一行开始,用户在其中输入“f”或“c”,然后按 Enter(行尾)。 nextLine() 消耗一切。

然后用户输入一个数字,然后按 Enter,代码使用 nextDouble() 读取 double 值。这消耗了双倍,但不消耗行尾。因此,如果您从 if block 中删除 nextLine(),则在 while 循环结束时调用 nextLine() 只会读取尚未使用的行尾,因此输入是一个空字符串。

由于空字符串既不是“f”也不是“c”,循环结束。

关于java - 在简单的 Java 程序上处理键盘输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21686590/

相关文章:

java - 为什么方法名以0结尾?

java - ARCore虚拟物体运动

Java "conversation"2 个线程之间 : Piped Input/Output streams

java - 自定义模型训练 opennlp

java - jComboBox获取所选项目错误

java - 方法错误包含 Vector java

python - 如何在没有 try/except 或 str.isdigit 的情况下检查字符串是否包含数字?

python - 提示输入,直到给出 2 个空行

html - 选择选项表单后自动填充文本表单值

c - 如何让 getchar() 不能得到我之前做的 ENTER?(在 C 中)