如何忽略双精度但将其余整数传递到 txt 文件中的数组中?

How do I ignore the double but pass the rest of the ints into an array in a txt file?

我正在做一个 Java 练习,它要求我读取一个包含数字(包括整数和双精度)的文件并将它们循环到一个数组中。但是,下面的代码只在第一个 double 处停止,然后就不再继续了。我需要做什么才能跳过那个 Double(以及稍后出现的)并继续显示整数?

int index = 0;
Scanner scan1 = new Scanner(new File(fileName));
while(scan1.hasNextInt()) {
    index = index + 1;
    scan1.nextInt();
}
int[] numbers = new int[index];
Scanner scan2 = new Scanner(new File(fileName));
for(int i = 0; i < index; i++) {
    numbers[i] = scan2.nextInt();
}
return numbers;

更新代码:

public int[] readNumbers2(String fileName) throws Exception {
    int index = 0;
    Scanner scan1 = new Scanner(new File(fileName)); 
    while(scan1.hasNext()) {
        if(scan1.hasNextInt()) {
            index = index + 1;
            scan1.nextInt();
        } else {
            scan1.next();
        }
    }
    int[] numbers = new int[index];
    Scanner scan2 = new Scanner(new File(fileName));
    for(int i = 0; i < index; i++) {
        numbers[i] = scan2.nextInt();
    }
    return numbers;
}

不是一个完整的答案,但这个循环可能更适合你:

while (scan1.hasNext()) {
    if (scan1.hasNextInt()) {
       // do something with int
    } else {
       // move past non-int token
       scan1.next();
    }
}

例如:

public static void main (String args[]) {
  Scanner scan1 = new Scanner("hello 1 2 3.5 there");
  while (scan1.hasNext()) {
    if (scan1.hasNextInt()) {
       // do something with int
       int i = scan1.nextInt();
       System.out.println(i);
    } else {
       // move past non-int token
       scan1.next();
    }
  }
}

打印:

 1
 2

这是基于您更新后的代码的版本 post:

Scanner scan1 = new Scanner("hello 1 2 3.5 there");
int index = 0;
while(scan1.hasNext()) {
    if(scan1.hasNextInt()) {
        index = index + 1;
        scan1.nextInt();
    } else {
        scan1.next();
    }
}

System.out.println("there are "+index+" integer tokens");

int[] numbers = new int[index];
int i = 0;

Scanner scan2 = new Scanner("hello 1 2 3.5 there");
while(scan2.hasNext()) {
    if(scan2.hasNextInt()) {
      numbers[i++] = scan2.nextInt();
    } else {
        scan2.next();
    }
}

for (int j = 0; j < numbers.length; j++) {
   System.out.println(numbers[j]);
}

打印

there are 2 integer tokens
1
2