2014-01-21 41 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()讀取輸入,包括單詞之間的空格(它直到行尾)