简体   繁体   中英

NoSuchElementException when trying to read integers from a file?

I'm trying to read integers from a .txt file and I get this error directly after input even though the while loop contains hasNextInt to make sure there is another integer in the file to read.

import java.util.Scanner;
import java.io.*;

public class Part2 {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String prompt = ("Please input the name of the file to be opened: ");
    System.out.print(prompt);
    String fileName = input.nextLine();
    input.close();
    Scanner reader = null;

    try{
      reader = new Scanner(new File(fileName)); 
    }

    catch(FileNotFoundException e){
      System.out.println("--- File Not Found! Exit program! ---"); 
    }

    int num = 0;
    while(reader.hasNextInt()){
      reader.nextInt();
      num++;
    }

    int[] list = new int[num];
    for(int i = 0; i<num; i++){
      list[i] = reader.nextInt(); 
    }

    reader.close();

    System.out.println("The list size is: " + num);
    System.out.println("The list is:");
    print(list);//Method to print out
    }//main
}//Part2

This is because in while loop , you have reached the end of the file.

 while(reader.hasNextInt()){
          reader.nextInt();
          num++;
        }

try to reinitialize it again after the while loop.

 reader = new Scanner(new File(fileName));

I think it's better to use List like

List list = new ArrayList();
int num = 0;
while(reader.hasNextInt()){
  list.add(reader.nextInt());
  num++;
}

/* this part is unnecessary
int[] list = new int[num];
for(int i = 0; i<num; i++){
  list[i] = reader.nextInt(); 
}
*/
//then
System.out.print(list);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM