这是一个简单的选题,然后答题的程序:
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
被分配一个空字符串InputS
与apple
进行比较,但它不相等(来自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/