Java输入一直为空?

标签 java input

这是一个简单的选题,然后答题的程序:

import java.util.Scanner;

public class Mains {

    static Scanner console = new Scanner(System.in);
    static Tof tof = new Tof();
    static int Ievel = 0;
    static int Input = 0;
    static boolean GAME = true;
    static boolean AT_START = true;
    static boolean IN_QUESTION = false;

    public static void main (String[] args) {
        while (GAME) {
            String InputS = "";

            if (AT_START) {
                System.out.println("Welcome to the game! Please select a number from 1 to 10.");
                AT_START = false;
            }

            if (!IN_QUESTION)               
                Input = console.nextInt();

            if (Input == -1) {
                GAME = false;
                console.close();
            } else {
                String question = tof.getQuestion(Input);
                String answer = tof.getAnswer(Input);

                System.out.println(question);

                IN_QUESTION = true;

                while (IN_QUESTION) {
                    InputS = console.nextLine();
                    if (InputS != console.nextLine()) {
                        if (InputS.equals(answer)) {
                            System.out.println("Correct!");
                        } else {
                            System.out.println("Incorrect. " + InputS + " " + answer);
                        }
                    }
                }
            }
        }
    }
}

问题:

当进入 IN_QUESTION 循环并编写答案时,它总是不正确的。 这是因为尽管设置了 console.nextLine(),但无论如何,InputS 变量始终为空。

为什么是空的?我该如何解决这个问题?

如果您需要其他类 Tof:http://pastebin.com/Fn5HEpL2

最佳答案

nextInt 没有获取整数后面的行终止符,并且您从控制台读取两次(第二次在 if 语句中)。

因此,如果您输入:

123
apple

发生以下情况:

  • Input 被分配值 123
  • InputS 被分配一个空字符串
  • InputSapple 进行比较,但它不相等(来自 InputS != console.nextLine() - 我不确定为什么它在那里)

您可以通过以下方式修复它:

  • console.nextInt();
    之后放置 console.nextLine();
    使用 Input = Integer.parseInt(console.nextLine()) 而不是 nextInt

  • 删除此内容 - if (InputS != console.nextLine())

关于Java输入一直为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17297571/

相关文章:

java - 动态设置 jTextField 值

Java - 在 jTextArea 中输入时,将焦点设置到相应的 jButton

php - datetime-local 值未出现在输入标签上

java - CardLayout 在 Java 中显示空白 JPanel

java - 获取 TextView 的高度

Javascript cookie 来记住输入值

javascript - 使用 d3 获取事件监听器中输入元素的值

html - 使用伪元素在有效输入字段上显示 ✓ 标记

java - Selenium:两个不同的浏览器返回两个不同的 xpath

c++ - 无法从字符串中获取数字输入