I am trying to make a program that processes "large" text file. The textfile displays 1000 lines, each for one faculty staff member. Each line contains firstname, lastname, rank and salary.
Link to the textfile: http://cs.armstrong.edu/liang/data/Salary.txt
The program should count the amount of employees by rank, and the total salary for each group. At the end, the total salary for each group should be displayed, along with the average salary for an employee with a given rank. I have not finished the entire program, and I'm currently making sure that the textfile is read correctly.
Code example below:
package ch12;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class Chapter_12_E25_ProcessLargeDataSet {
public static void main(String[] args) throws IOException {
int assistantCount = 0;
int associateCount = 0;
int fullCount = 0;
int facultyCount = 0;
double assistantSalary = 0;
double associateSalary = 0;
double fullSalary = 0;
double facultySalary = 0;
try {
URL url = new URL("http://cs.armstrong.edu/liang/data/Salary.txt");
Scanner input = new Scanner(url.openStream());
while (input.hasNext()) {
String firstName = input.next();
String lastName = input.next();
String rank = input.next();
double salary = input.nextDouble();
if (rank.contains("assistant")) {
assistantCount++;
System.out.println("Rank is " + rank + " and salary is " + salary);
} else if (rank.contains("associate")) {
associateCount++;
System.out.println("Rank is " + rank + " and salary is " + salary);
} else {
fullCount++;
System.out.println("Rank is " + rank + " and salary is " + salary);
}
}
input.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
System.exit(1);
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
System.exit(2);
}
}
}
The line double salary = input.nextDouble()
causes an InputMismatchException
. If i change the variable salary to a String
instead of a double
, the salary is read correctly. If i change double salary = input.nextDouble()
into double salary = Double.parseDouble(input.next())
, I get the right double
value. It doesen't bother me to use this approach, but I'm just curious why the scanner
does not accept the salaries as a double
value.
Can anyone please explain why?
Also, a sub question that is off-topic. If I change the filename Salary.txt in the argument for the URL object
to a file that does not exists, FileNotFoundException
in catch statement
nr2 is not thrown, but instead an InputMismatchException
is thrown. Why is the InputMismatchException
thrown instead of FileNotFoundException
?
Most likely your scanner uses the wrong locale. Based on the values of your Salary.txt, you simply have to change your scanner's locale to english. Try this:
import java.util.Locale;
...
Scanner input = new Scanner(url.openStream());
input.useLocale(Locale.ENGLISH);