Altering input for HashMap in Java using split() method with array without crashing

1081 views java

working on my current lab and seemed to have run into a slight roadblock. I have never used the split() method up until now and am unsure on how to remedy my problem. Here is a snippet of my code to get started explaining.

Map<Integer, Employee> employeeMap = new HashMap<>();

    while (true) 

        line = scanner.nextLine();

        if (line.startsWith("$")) 
         String[] employeeTracker = line.split(" ");

            Employee employee = new Employee(++empCount, employeeTracker[0], employeeTracker[1], employeeTracker[2], Double.parseDouble(employeeTracker[3]), 
            Integer.parseInt(employeeTracker[4]), Boolean.parseBoolean(employeeTracker[5]));

          employeeMap.put(employee.getId(), employee);

Original example input: (this was when my Employee employee = new Employee had 4 arguments for input. I have now increased it to 6 for 2 additional inputs needed from new class being added.

John Smith 1234567 10.55

New input im trying to get to work.

*John Smith 1234567 10.55 1 true

The issue currently is now that I have made the program accept this new input, I need it to also just work when the old type of input is put in (with just 4 arguments). My first thought is to give some dummy value to those other 2 last arguments when this occurs to prevent crashing, but I have had little luck doing so. Thus, I search for any welcoming suggestions.

Thanks in advance! I would be glad to post any additional code or answer any other questions as necessary.

answered question

a simple condition checking could do the job, like if(employeeTracker.length == 5)

Please also share the code you've tried that did not work and state the error you got.

1 Answer


You can use the length of the employeeTracker array to test what the input is

if (employeeTracker.length >= 6) {
     // new inoput
else {
    // old input
    // use dummy values

posted this

Have an answer?


Please login first before posting an answer.