Reputation: 11
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
Upvotes: 0
Views: 109
Reputation: 584
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);
Upvotes: 0
Reputation: 267
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));
Upvotes: 1