字符串输入无法正常工作

时间:2014-12-02 17:31:13

标签: java string input

我所要做的就是编写代码,要求用户输入以空格分隔的数字序列。

它应该很简单,而且对于我的(公认有限的)知识,以下代码应该可以正常工作:

    System.out.print("How many numbers? ");
    int n = input.nextInt();
    System.out.print("Please enter " + n + " numbers (seperated by spaces) ");
    String numbers = input.nextLine();

除非它不起作用。我为n输入整数,然后当程序要求我输入一系列数字时,我无法输入任何内容,字母,数字,任何东西。

这是多远:

How many numbers? 8
Please enter 8 numbers (seperated by spaces) 

虽然它应该接受我对String变量号的下一个输入,但肯定没有这样做。

2 个答案:

答案 0 :(得分:0)

如果您在第一次输入后enter,则将其作为新行,因此请添加另一个readline以消除该情况

        System.out.print("How many numbers? ");
        int n = input.nextInt();
        input.nextLine();
        System.out.print("Please enter " + n + " numbers (seperated by spaces) ");
        String numbers = input.nextLine();

答案 1 :(得分:0)

您应该将行输入解析为整行:

int n;
for(boolean read = false; !read; ) {
    System.out.print("How many numbers? ");
    String line = input.nextLine();
    // parse line to n and set read on success
    // one possibility (not the only way)
    try {
        n = Integer.parseInt(line);
        read = true;
    } catch (NumberFormatException e) {
        System.out.println("\"" + line + "\" is not an integer");
    }
}
for(boolean read = false; !read; ) {
    System.out.print("Please enter " + n + " numbers (seperated by spaces) ");
    String line = input.nextLine();
    int parsedInts = 0;
    for(int i = 0; i < n; ++i, ++parsedInts) {
        // try to parse the next int from line and break on failure
        ...
    }
    read = parsedInts == n;
}