2017-06-05 21 views
0

請我有一個proble,這是我到目前爲止的代碼我不能把串中的字符串數組的第一個位置

System.out.println("Please give alue for the table"); 
    int value = scanner.nextInt(); 

    String[] StringArray = new String[value]; 

    for (int i=0; i<value; i++) 
    { 
     System.out.println("Please insert string for the position:"+(i+1)); 
     StringArray[i] = scanner.nextLine(); 
    } 
} 

而且我的輸出是

Please give alue for the table 
3 
Please insert string for the position:1 
Please insert string for the position:2 

爲什麼我不能插入字符串到位置1和我的程序讓我在位置2和之後? 我需要幫助,我不能unsterstand。 謝謝你的時間。

回答

2

因爲讀取int不會消耗整個緩衝區,但仍然有一個\n左側。根據文檔,nextLine的讀數爲\n,所以您第一次只會得到一個空字符串。

您可以輕鬆地在nextInt()之後加入scanner.nextLine()解決這個問題:

System.out.println("Please give alue for the table"); 
int value = scanner.nextInt(); 

scanner.nextLine(); // get rid of everything else left in the buffer 

String[] StringArray = new String[value]; 

for (int i=0; i<value; i++) 
{ 
    System.out.println("Please insert string for the position:"+(i+1)); 
    StringArray[i] = scanner.nextLine(); 
} 
+0

非常感謝隊友,我解決我的問題 –

+0

@ILOVEJAVA如果它幫助你,請記住[標記答案已被接受](https://meta.stackexchange.com/a/5235/208693) – BackSlash

1

可以使用的BufferedReader的InputStreamReader和:)

System.out.println("Please give alue for the table"); 
    BufferedReader scanner=new BufferedReader(new InputStreamReader(System.in)); 
    int value = Integer.parseInt(scanner.readLine()); 
    String[] StringArray = new String[value]; 

    for (int i=0; i<value; i++) 
    { 
     System.out.println("Please insert string for the position:"+(i+1)); 
     StringArray[i] = scanner.readLine(); 

    } 
+0

感謝您的時間我的朋友,它也會幫助我 –

相關問題