2014-01-21 40 views
2

我有一系列的问题需要创建一副闪存卡。到目前为止,只要问题没有空格,我可以收集问题和答案。如果问题确实有空格,答案会被跳过,但如果答案有空格,则没有问题。这里是我的代码片段:用扫描仪捕捉空间?

 
    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 
+1

在'next'后面使用'Line'。 –

回答

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

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

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