2017-06-05 14 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

感谢您的时间我的朋友,它也会帮助我 –

相关问题