Skip to main content

Read input file without main

1 reply [Last post]
djangdal
Offline
Joined: 2009-11-21
Points: 0

Hi, i have been trying to read from a text file. When i had it in the main class it worked fine, but when i tried to create a class that would read from the text file it says it cant find the file. Do you have to have the "FileReader" in the main class and how can i solve this problem?

"new FileReader("numberOfPlayers.txt");" gets red and when i hold on it in eclipse it say "Unhandled exception type FileNotFoundException"

import java.io.FileReader;
import java.util.Scanner;

public class NumberOfPlayers {
FileReader file = new FileReader("numberOfPlayers.txt");
Scanner scan = new Scanner(file);
int[] numberOfPlayers = new int[9];

public NumberOfPlayers() {
}
public NumberOfPlayers(int numberOfPlayers[]) {
this.numberOfPlayers = numberOfPlayers;
}
public int[] getNumberOfPlayers() {
for (int i = 0; i < 9; i++) {
int line = Integer.parseInt(scan.nextLine());
numberOfPlayers[i] = line;
}
return numberOfPlayers;
}
}

Message was edited by: djangdal

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
peter__lawrey
Offline
Joined: 2005-11-01
Points: 0

Its not what the error means.
The COMPILE time error means the new Filereader can throw a checked exception you are not catching. The simplest thing to do is to move the initialisation to the constructor and have the constructor throw FileNotFoundException.