Reputation: 21
I am using a file that has a first and last name and four sales numbers. I have an array created. I want to use all the people and sales figures to be displayed. Here is the format of the file.
Willow Mary
154 189.5 95 76 63.51
Here's is what I was trying. It keeps going to my catch block.
import java.io.File;
import java.util.Scanner;
public class Assignment10 {
public static final int NUM_SALESPEOPLE = 20;
public static void main(String[] args) {
SalesPerson[] list = new SalesPerson[NUM_SALESPEOPLE];
try {
int people = 0;
Scanner fileInput = new Scanner(new File("A10.txt"));
while (fileInput.hasNext()) {
String firstName = fileInput.nextLine();
String lastName = fileInput.nextLine();
double firstSales = fileInput.nextDouble();
double secondSales = fileInput.nextDouble();
double thirdSales = fileInput.nextDouble();
double fourthSales = fileInput.nextDouble();
SalesPerson person = new SalesPerson(firstName, lastName,
firstSales, secondSales, thirdSales, fourthSales);
list[people] = person;
people++;
}
} catch (Exception ex) {
System.out.println("Error opening file.");
}
Upvotes: 0
Views: 52
Reputation: 234807
If your file is the format that you say, you are reading too many lines when you read each person. This code:
String firstName = fileInput.nextLine();
String lastName = fileInput.nextLine();
reads two lines from the file, yet the name appears on a single line. You are probably running out of lines when you get within three lines of the end of the file or else (more likely) trying to parse a line containing a name as if it were double values.
You also need to consume any trailing white space (including the newline) after reading the doubles. Try fileInput.skip("\\w");
.
Instead, read the entire line of doubles as a single line and break it apart with code (e.g., using split(" ")
) or by parsing in some other way.
Upvotes: 2
Reputation: 32953
This code
String firstName = fileInput.nextLine();
String lastName = fileInput.nextLine();
eats up 2 lines, so the following nextDouble() calls wont go where you want them to go.
Also
} catch (Exception ex) {
System.out.println("Error opening file.");
}
Is not always true, because you catch all Exception
's not only the ones that are file related. At the very least also output the message your Exception is generating:
} catch (Exception ex) {
System.out.println("Something went wrong: " + ex.getMessage() );
}
Better still, catch all kinds of Exceptions generated in your program separately and provide a sensible error message, or recovery behavior per Exception type.
Upvotes: 0