Search code examples
javaurliojava.util.scanner

Calculating total and average salary


The question says: A university posts its employees' salaries at http://cs.armstrong.edu/liang/data/Salary.txt. Each line in the file consists of a faculty member's

  • first name,
  • last name,
  • rank,
  • and salary.

Write a program to display the total salary for

  • assistant professors,
  • associate professors,
  • full professors,
  • and all faculty respectively,

and display the average salary for

  • assistant professors,
  • associate professors,
  • full professors,
  • and all faculty respectively.

And my code thus far:

import java.util.Scanner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class Salary {
    public static void main(String[] args) throws MalformedURLException{
        URL salary = new URL("http://cs.armstrong.edu/liang/data/Salary.txt");
        try{
            Scanner read = new Scanner(salary.openStream());
            while(read.hasNextLine()){
                String line = read.nextLine();
                System.out.println(line); //Testing to see if the URL works
            }
            read.close();
        } catch(IOException e){
            e.getStackTrace();
        }
    }
}

What I was hoping I could do would be to create objects from each line of text and then group them together based on their rank and go from there, however, I honestly can't figure out how to do that for the life of me. I think once I get everything grouped together the way I want it then I should be able to figure out the rest, but I'm not sure if I should even be doing all of this in the main method. Any help would be appreciated.


Solution

  • Not going to do your homework, but this might help you:

    • line.split("\\s") does split the line into an array of String, separated by white-space.
    • Double.valueOf(string) converts a string into a double. Will throw an Exception if the String is actually not a number.
    • Then - as you already suggested - putting the results in immutable data classes for easier processing should do the trick.