使用扫描仪在一行中读取多个数字

时间:2021-01-23 21:51:26

I need to read multiple numbers (don't know how many numbers I'm going to read, but I know they are at most six numbers) from a single line using a Scanner. I tried something found on the net but I couldn't find a solution. The reading stops when the user writes -1. Here's what I wrote up to now:

我需要使用扫描仪从一行读取多个数字(不知道我要阅读多少个数字,但我知道它们最多有六个数字)。我尝试在网上找到的东西,但我找不到解决方案。当用户写入-1时,读取停止。这是我现在写的:

Scanner read = new Scanner(System.in);
int i;
float buffer[] = new float[6];

while (read.nextInt() != -1) {
            if (read.hasNextInt()) {
                buffer[i] = read.nextInt();
                i++;
            } else {
                break;
            }
        }

When I try to run this, I get a NoSuchElementException, but I don't understand why. What's wrong with this code? How can I correct this? Thanks in advance.

当我尝试运行它时,我得到一个NoSuchElementException,但我不明白为什么。这段代码出了什么问题?我怎么能纠正这个?提前致谢。

2 个解决方案

#1


2  

Because you aren't checking if the Scanner has another int (and a Scanner doesn't return -1 when it does not have another element). This

因为您没有检查Scanner是否有另一个int(并且当一个Scanner没有另一个元素时,它不会返回-1)。这个

while (read.nextInt() != -1) {

needs to be something like

需要像这样的东西

while (read.hasNextInt()) {
    int val = read.nextInt();
    if (val == -1) {
        break;
    }
    buffer[i] = val;
    i++;
}

#2


1  

Or you can read line once, and split it in integers

或者您可以读取一次行,并将其拆分为整数

   line=scanner.nextLine();

   // split there
   String elements[]=line.split("\\W+");

   // convert to int    
   for (int i=0;i<elements.length;i++)
       ints[counter++]=Integer.parseInt(elements[i]);

   // check
   for (int i=0;i<counter;i++)
       System.out.println("INT ["+i+"]:"+ints[i]);

#1


2  

Because you aren't checking if the Scanner has another int (and a Scanner doesn't return -1 when it does not have another element). This

因为您没有检查Scanner是否有另一个int(并且当一个Scanner没有另一个元素时,它不会返回-1)。这个

while (read.nextInt() != -1) {

needs to be something like

需要像这样的东西

while (read.hasNextInt()) {
    int val = read.nextInt();
    if (val == -1) {
        break;
    }
    buffer[i] = val;
    i++;
}

#2


1  

Or you can read line once, and split it in integers

或者您可以读取一次行,并将其拆分为整数

   line=scanner.nextLine();

   // split there
   String elements[]=line.split("\\W+");

   // convert to int    
   for (int i=0;i<elements.length;i++)
       ints[counter++]=Integer.parseInt(elements[i]);

   // check
   for (int i=0;i<counter;i++)
       System.out.println("INT ["+i+"]:"+ints[i]);