用Scanner捕捉空间?

时间:2014-01-21 16:49:14

标签: java string java.util.scanner

我有一系列问题要求创建一副闪存卡。到目前为止,如果问题没有空格,我可以收集问题和答案。如果问题确实有空格,则跳过答案,但如果答案有空格,则没有问题。以下是我的代码片段:

    System.out.println("What is the question for number " + (cards + 1) + "?");
    question = in.next();
    System.out.println("What is the answer for number " + (cards + 1) + "?");
    answer = in.next();

以下是问题和答案中带空格的结果输出:

What is the question for number 1?
This is a question
What is the answer for number 1?
What is the question for number 2?
x
What is the answer for number 2?
This is an answer
What is the question for number 3?
X

2 个答案:

答案 0 :(得分:3)

不使用next()方法,而是使用nextLine()来捕获整行,而不只是下一个字:

System.out.println("What is the question for number " + (cards + 1) + "?");
question = in.nextLine();
System.out.println("What is the answer for number " + (cards + 1) + "?");
answer = in.nextLine();

这有帮助吗?

答案 1 :(得分:1)

next()只读取输入直到空格。它无法读取由空格分隔的单词。

nextLine()读取包含单词之间空格的输入(它读到行尾)