2017-08-12 121 views
0

我不明白爲什麼當程序被循環條件終止時,我得到了下一個元素的輸出。如果我輸入3,程序終止詢問第三個值,但沒有輸入任何內容。當您使用in.nextInt()它只讀取從輸入流的整數值有什麼問題沒有得到所需的輸出

Scanner in = new Scanner(System.in); 
    System.out.println("number of word you want to input"); 
    int NumberOfWord = in.nextInt(); 
    System.out.println("input the words-->"); 
    for (int i = 0; i <= NumberOfWord; i++) { 
     userInput[i] = in.nextLine(); 
     System.out.println("enter your "+(i+1)+"th word"); 
+0

'nextInt開始(這是發生問題的護理)'在輸入的數字後面結束,並且需要另一個'nextLine()'來完成該行的其餘部分(可能爲空)... –

+0

正確聲明userInput。它是未定義的。 – Tehmina

回答

1

。但它不會讀取之後出現的換行符。

在循環中調用nextLine()方法之前,可以使用虛擬的in.nextLine(),該方法用於讀取整數值後面的換行符。

int NumberOfWord = in.nextInt(); 
in.nextLine(); 
System.out.println("input the words-->"); 
for (int i = 0; i < NumberOfWord; i++) { 
    userInput[i] = in.nextLine(); 
    System.out.println("enter your " + (i + 1) + "th word"); 
} 

另一種解決方法是使用nextLine()方法本身來讀取整數值。 nextLine()方法從流中讀取整行,以換行符作爲終止點(也包括換行符)。因此,需要在使用nextInt()

int NumberOfWord = Integer.parseInt(in.nextLine()); 
System.out.println("input the words-->"); 
for (int i = 0; i < NumberOfWord; i++) { 
    userInput[i] = in.nextLine(); 
    System.out.println("enter your " + (i + 1) + "th word"); 
} 

而且在你的循環條件,其中使用<=這將要求一個更高的價值爲你的循環是從0

+0

我想要的是...不打印最後一個輸出,它要求另一個輸入 –

+0

@RafiUddin編輯了ans並解決了問題。 – Joe

+0

謝謝....但是in.nextLine();沒有 –