Java输入一直是空的?
这是一个简单的问题选择,然后回答程序:Java输入一直是空的?,java,input,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 b
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循环并编写答案时,它总是不正确的。
这是因为InputS变量始终为空,而console.nextLine()被设置为空
为什么是空的?我该如何解决这个问题
如果您需要另一个类Tof:您可以调用
console.nextLine
两次。这意味着你读了一行,你会检查,另一行你不会。这可能不是你想要的。还要注意的是,您对nextInt
的首次呼叫不会占用您在输入号码后按下的换行符。在这之后,但在主循环之前,您需要一个nextLine
一些一般性意见:
- 大写名称仅用于常量,因此变量应为小写李>
- 你应该使用局部变量而不是静态变量。现在这不会伤害你,但很快就会李>
nextInt
没有在整数后面获取行终止符,您从控制台读取了两次(第二次是在if语句中)
因此,如果您输入:
123
apple
发生以下情况:
被分配一个值Input
123
被分配一个空字符串输入
与InputS
进行比较,它不相等(来自apple
-我不确定它为什么在那里)InputS!=console.nextLine()
- 放置
console.nextLine()代码>在
console.nextInt()之后代码>
或
使用
而不是Input=Integer.parseInt(console.nextLine())
nextInt
- 删除此-
if(InputS!=console.nextLine())
- 您从控制台读取了两次。这应该起作用:
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
问题是新行字符未被nextLine()
方法读取,因此它保留在扫描仪缓冲区中,下次调用nextLine()
时,首先打印该字符
以下是解决问题的方法:
//empty the newline character from the scanner
console.nextLine();
while (IN_QUESTION) {
InputS= console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
您的控制台输入是什么?此外,应避免以大写字母开头变量名。输入应为输入,输入应根据代码约定输入。大写的静态变量也应该遵循正确的代码约定。所有大写字母通常仅用于常量。如果您遵循代码约定,其他java开发人员将更容易解密您的代码。当我打印输入时,打印将为空。