2015-12-22 23 views
1

對於Java編程而言是新的。我只想打印由用戶輸入的n個字符串,其中「n」是由用戶輸入的測試用例的數量。所以下面是我的代碼...但nextLine()方法在基本情況下(即在int i=0)沒有從用戶處獲得輸入。 代碼java.util.scanner方法不在for循環中的基本情況下執行?

import java.util.Scanner; 
import java.io.InputStreamReader; 

     public class Stringprint{ 
     public static void main(String[] args){ 
      String str; 
      int testcase; 
      Scanner scanIn = new Scanner(System.in); 
      System.out.println("Enter the number of testcases :"); 
      testcase = scanIn.nextInt(); 
      for(int i = 0; i < testcase ; i ++){ 

       System.out.println("Enter the String" + i + ":"); 
       str = scanIn.nextLine(); 
       System.out.println(string); 
    } 
    } 

} 

出來放上面的代碼也越來越像:

Enter the number of testcases : 
4 

Enter the String0: 

Enter the String1: 

hello 

hello 

Enter the String2: 

hai 

hai 

Enter the String3: 

bye 

bye 

所以我在哪裏得到wrong..why它不是在i=0要求輸入字符串?我在這裏做錯了什麼?

+1

問題歸結於nextLine()。使用next(),它會正常工作.. –

+2

使用next(),nextInt()或其他nextFoo()方法後跳過nextLine()的可能重複(http://stackoverflow.com/questions/13102045/ skip-nextline-after-using-next-nextint-or-other-nextfoo-methods) – resueman

+0

This may clear:http://stackoverflow.com/a/20190113/5188230 –

回答

0

Scanner.nextInt()將光標前進4,但過去換行。

當第一次調用Scanner.nextLine()時,輸入以新行開始,因此它返回一個空行。

1

在呼叫scanIn.nextInt()之後和循環前嘗試使用scanIn.nextLine()。在致電nextInt()後,該線路尚未結束。因此,新行字符由nextLine()調用返回。

+0

謝謝你..解答解決了我的問題:) –

0

一個簡單的修正:

添加 'scanIn.nextLine();' 'testcase = scanIn.nextInt();'之後'吃掉nextInt()沒有使用的'\ n'字符。

相關問題