2013-09-07 3 views
0

updateEmployees (PersonnelManager pm) 메소드는 텍스트 파일을 읽고 파일에 각 행의 첫 번째 문자 (3 가지 가능성 있음)에 따라 다른 코드를 실행합니다. PersonnelManager 클래스와 Employee 클래스는 문제를 일으키지 않으므로 여기에 포함시키지 않습니다.Java split() 메소드가 다시 작동하지 않습니다.

N Mezalira, 루카스 H 40000

R 킨제이

N 프라이스 레인의 50

R & D 5

4

다음은 샘플 입력 파일은

방법은 다음과 같습니다. (파일 및 스캐너 객체 입력 파일의 5 선이 있기 때문에

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

, while 루프가 5 번 실행해야)하는 방법에서 선언,하지만 일이 발생하지거야. 입력 파일의 4 번째 줄에 도달하면 : "Pryce, Lane s 50"코드의 25 행에 "java.lang.StringIndexOutOfBoundsException"오류가 발생합니다.

문제는 라인 (24, 25)에서 발생한다 : 입력 된 4 라인

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 

에서 "라인"문자열이 예상대로 5 개 문자열로 분할되지 않는다. 단어는 [0]이고 "n"과 같습니다. 내가 이해하지 못하는 것은이 프로그램이 동일한 3 줄의 코드를 사용하여 처음 3 줄의 입력을 나누었을 때 왜 4 줄에서 작동하지 않는 것입니까?

제가

N Mezalira, 루카스 H 40000

R 명령 번째 발생을 제거 킨제이

거라고 5

"N으로 입력 파일을 변경할 때 ", 그것은 작동합니다. 실제로 동일한 명령 ("n", "r"또는 "d")을 두 번 이상 사용하는 입력 파일을 사용할 때마다 명령이 두 번째 발생하는 행은 1 문자열로만 분할됩니다. 줄에 첫 번째 토큰 (이 경우 "n", "r"또는 "d")을 포함합니다.

제 설명에서 분명히 밝혀졌습니다. 왜 이런 일이 일어날 지 아는 사람이 있으면 도와주세요.

+2

실제 코드가 아닐 수도 있습니다. 상단에있는'File'과'Scanner'는'try' 블록 안에 선언되어 즉시 범위를 벗어나므로 나머지 코드에서는 사용할 수 없습니다. 이 코드가 의미하는 바를 의미하지는 않습니다 .- –

+0

파일과 스캐너가 메서드 밖으로 선언되었습니다. 방금 게시 한 내용을 여기에 추가했습니다. 편집 해 보겠습니다. –

+3

줄이 실제로 보이는지 _exactly_ 보이고, 필드 사이에 정확히 하나의 공백이 있습니까? 'split()'호출은 실제로 여러 개의 공백을 허용하기 위해'split ("\\ s +")'이어야합니다. –

답변

2

split() 전화는 필드간에 여러 공백을 허용하려면 실제로 split("\\s+")이어야합니다.

관련 문제