Java split()方法不会再次运行

时间:2013-09-07 03:24:59

标签: java regex

方法updateEmployees(PersonnelManager pm)读取文本文件,并根据文件中每行的第一个字符(有3个可能性)执行不同的代码。 PersonnelManager和Employee类在问题上没有发挥作用,这就是为什么我不在这里包括它们。这是一个示例输入文件:

  

n Mezalira,Lucas h 40000

     

r 5

     

d Kinsey

     

n Pryce,Lane s 50

     

r 4

这是方法: (File和Scanner对象是从方法中声明的)

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;
}

由于输入文件中有5行,while循环应执行5次,但事实并非如此。当它到达输入文件中的第4行:“n Pryce,Lane s 50”时,我在代码的第25行得到“java.lang.StringIndexOutOfBoundsException”错误。

问题出现在第24和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

对于第4行输入,“line”字符串不会像它应该分成5个字符串。它只被分成一个,在单词[0]中,它等于“n”。 我不明白的是程序使用相同的代码行来分割前三行输入的字符串,为什么它不能在第四行工作?

当我将输入文件更改为

  

n Mezalira,Lucas h 40000

     

r 5

     

d Kinsey

删除第二次出现的命令“n”,它可以工作。实际上,每次我使用不止一次使用相同命令(“n”,“r”或“d”)的输入文件时,第二次发生命令的行只会被分成1个字符串。包含第一个标记(在本例中为“n”,“r”或“d”)。

我希望我的解释清楚。如果有人知道为什么会这样,请帮助。

1 个答案:

答案 0 :(得分:2)

您的split()来电应该是split("\\s+"),以允许字段之间存在多个空白。