我无法将String放在字符串数组的第一个位置

时间:2017-06-05 20:58:48

标签: java arrays loops

请问我有问题,这是我目前的代码

    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和之后? 我需要帮助,我不能解开。 谢谢你的时间。

2 个答案:

答案 0 :(得分:2)

因为读取int不会消耗整个缓冲区,而缓冲区仍然有\n。根据文档,nextLine会一直读到\n,所以第一次只能得到一个空字符串。

您可以在scanner.nextLine()

之后添加nextInt()轻松解决此问题
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();
}

答案 1 :(得分: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();

    }