Java 字符串输入无法正常工作

Java 字符串输入无法正常工作,java,string,input,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()

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

它应该很简单,就我(承认有限)所知,以下代码应该可以正常工作:

    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) 

虽然它应该接受我对字符串变量数的下一次输入,但它肯定不会这样做。

在您的情况下,当您在第一次输入后输入
时,它会将其作为新行,因此添加另一个
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();

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

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;
}
intn;
for(布尔读取=false;!读取;){
系统输出打印(“多少个数字?”);
String line=input.nextLine();
//将行解析为n,并将读取设置为成功
//一种可能性(不是唯一的方法)
试一试{
n=整数.parseInt(行);
读=真;
}捕获(数字格式){
System.out.println(“\”+行+“\”不是整数);
}
}
for(布尔读取=false;!读取;){
系统输出打印(“请输入“+n+”数字(用空格分隔)”;
String line=input.nextLine();
int parsedInts=0;
对于(int i=0;i
您确定nextInt在解析int之后删除了换行符吗?我甚至不知道这意味着什么。我正在学习java入门课程,我甚至不认为我们已经讨论过了。当然,除非我们的亚裔教授顺便提到了这一点,我没有听清楚,否则你应该用正确的语言标记你的问题,以获得更好的结果。这是java吗?所以我在谷歌上搜索了一下,确实是新行的问题。谢谢你@BeyelerStudios