Java split() method won't work a second time

Lucas Mezalira

The method updateEmployees(PersonnelManager pm) reads a text file and depending on the first character of each line (there are 3 possiblities) on the file, it executes different code. The PersonnelManager and Employee classes have no play in the problem, that's why I'm not including them here. Here is a sample input file:

n Mezalira, Lucas h 40000

r 5

d Kinsey

n Pryce, Lane s 50

r 4

Here is the method: (the File and Scanner objects are declared out of the method)

public static boolean updateEmployees(PersonnelManager pm) {
    
    try 
    {
    file = new File(updates);
    in = new Scanner(file);
    }
    
    catch (FileNotFoundException e) 
    {
        System.out.println("Could not load update file.");
        return false;
    }
    
    int currentLine = 1; //Keep track of current line being read for error reporting purpose
    while (in.hasNext()) {
        String line = in.nextLine();
        
        //Check the type of update the line executes
        
        //Update: Add new Employee
        if (line.charAt(0) == 'n') {
    
            String[] words = line.split("\\s"); //Split line into words. Index [0]: update type.  [1]: last name.   [2]: first name.   [3]: employee type.  [4]: wage.
            words[1] = words[1].substring(0, words[1].length() - 1); //remove comma from last name
    
            if (words.length != 5) { //If there are not 5 words or tokens in the line, input is incorrect.
                System.out.println("Could not update. File contains incorrect input at line: " + currentLine);
                return false; 
            }
            
            if (words[3].equals("s"))  //if employee is type SalariedEmployee
                pm.addEmployee(new SalariedEmployee(words[2], words[1], Double.parseDouble(words[4])));
            
            
            else if (words[3].equals("h"))  //if employee is type HourlyEmployee
                pm.addEmployee(new HourlyEmployee(words[2], words[1], Double.parseDouble(words[4])));
            
            else {
                System.out.println("Could not update. File contains incorrect input at line: " + currentLine);
                return false;
            }
            //Display information on the console
            System.out.println("New Employee added: " + words[1] + ", " + words[2]);
        }
        
        //Update: Raise rate of pay
        if (line.charAt(0) == 'r') {
            String[] words = line.split("\\s"); //Split line into words. Index [0]: update type.  [1]: rate of wage raise
            if (Double.parseDouble(words[1]) > 100.0) { //If update value is greater than 100
                System.out.println("Error in line:" + currentLine + ". Wage raise rate invalid.");
                return false;
            }
            
            for (int i =0; i<pm.howMany(); i++) { //Call raiseWages() method for all employees handled by the pm PersonnelManager
                pm.getEmployee(i).raiseWages(Double.parseDouble(words[1]));
            }
            
            //Display information on the console
            System.out.println("New Wages:");
            pm.displayEmployees();
            
        }
        
        //Update: Dismissal of Employee
        if (line.charAt(0) == 'd') {
            String[] words = line.split("\\s"); //Split line into words. Index [0]: update type.  [1]: last name of employee
            if (words.length != 2) { //If there are not 2 words or tokens in the line, input is incorrect.
                System.out.println("Could not update. File contains incorrect input at line: " + currentLine);
                return false; 
            }
            
            String fullName = pm.getEmployee(words[1]).getName(); //Get complete name of Employee from last name
            pm.removeEmployee(words[1]);
            
            //Display information on the console
            System.out.println("Deleted Employee: " + fullName);
        }
        
        currentLine++;
    }
    return true;
}

Since there are 5 lines in the input file, the while loop should execute 5 times, but that's not what happens. when it reaches the 4th line in the input file: "n Pryce, Lane s 50", I get an "java.lang.StringIndexOutOfBoundsException" error, in line 25 of the code.

The problem occurs at lines 24 and 25:

String[] words = line.split("\\s"); //Split line into words. Index [0]: update type.  [1]: last name.   [2]: first name.   [3]: employee type.  [4]: wage.
words[1] = words[1].substring(0, words[1].length() - 1); //remove comma from last name

For the 4th line of input, the "line" String is not split in 5 Strings as it should. It is only split into one, which is in words[0] and it equals "n". What I don't understand is the program used the same line of code to split the String for the first 3 lines of input, why doesn't it work on the 4th line?

When I change the input file to

n Mezalira, Lucas h 40000

r 5

d Kinsey

removing a second occurrence of the command "n", it works. In fact, every time I use an input file that uses the same command ("n", "r" or "d") more than once, the line where the command happens the second time will only be split into 1 string. containing the first token ( int this case "n", "r", or "d") on the line.

I hope I was clear in my explanation. If anyone know why this happens, please help.

Jim Garrison

Your split() call should really be split("\\s+") to allow for multiple blanks between fields.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Java won't read my second process

분류에서Dev

RequestContext won't work

분류에서Dev

AJAXify won't work on phpBB?

분류에서Dev

Program won't work in FireFox

분류에서Dev

Fade in Function Won't Work

분류에서Dev

Java Class.forName won't compile. Getting "cannot find symbol symbol : method"

분류에서Dev

Why won't this regexp in htaccess work properly?

분류에서Dev

Alsamixer won't work with bluetooth device

분류에서Dev

Post variables with ajax won't work

분류에서Dev

Simple class won't work in C++

분류에서Dev

Laravel named routes won't work on wampserver

분류에서Dev

Why won't the routing work in this code?

분류에서Dev

Now visudo won't work at all

분류에서Dev

Why won't this MySQL stored procedure work?

분류에서Dev

The hover for my buttons and links won’t work

분류에서Dev

My update queries won't work

분류에서Dev

For /F "skip=0" won't work as expected

분류에서Dev

Windows 7 computer won't boot and recovery doesn't work

분류에서Dev

Android ListView Onclick Intent data delay (work in second time click)

분류에서Dev

Laravel facade Slug won't work for non English?

분류에서Dev

Graphql Query with express and Mongodb won't work properly?

분류에서Dev

Why std::basic_fstream<unsigned char> won't work?

분류에서Dev

jQuery delay and javascript settimeout won't work with facebook button

분류에서Dev

Google Maps won't work when API key is provided

분류에서Dev

VBA - Conditional formatting: Excel 2010 won't work, Excel 2013 will

분류에서Dev

changing genemu jquery datepicker localization seetings won't work

분류에서Dev

Lightbox won't work when my site css page is linked

분류에서Dev

Wi-Fi just won't work on Ubuntu 17.10

분류에서Dev

boot menu shows up but Ubuntu won't work

Related 관련 기사

뜨겁다태그

보관