2013-06-21 76 views
0

我明白没有这样的元素异常,但我不明白我做错了什么。我需要使用Tokenizer,以便可以读取诸如“A-902”或“S-823”等令牌并在0处标识字符以确定员工所在的部门.Information.txt包含如下条目:没有这样的元素异常

简河流,A-902,2001年5月16日,1,16.25
鲍勃·考克斯,S-823,1990年6月21日,2,17.50

import java.util.Scanner; 
import java.io.*; 
import java.util.StringTokenizer; 

    public class CreateFile { 

    public static void main(String[] args)throws FileNotFoundException{ 

     File newFile = new File("Information.txt"); 
     Scanner readFile = new Scanner(newFile); 
     PrintWriter outFile = new PrintWriter("Department.txt"); 

     String[] employees = new String[9]; 

     while(readFile.hasNext()){ 

      for(int i=0; i<employees.length; i++){ 
       employees[i] = readFile.nextLine(); 
      } 
     } 

     for(int k=0; k<employees.length; k++){ 

     StringTokenizer token = new StringTokenizer(employees[k],","); 

     while(token.hasMoreTokens()){ 

       outFile.print(token.nextToken()); 

       if(token.nextToken().charAt(0)=='A'){ 
        outFile.print(token.nextToken()); 
        outFile.print("Accounting "); 
       }else{ 

       if(token.nextToken().charAt(0)=='H'){ 
        outFile.print(token.nextToken()); 
        outFile.print("Human Resources "); 
       }else{    

       if(token.nextToken().charAt(0)=='P'){ 
        outFile.print(token.nextToken()); 
        outFile.print("Production "); 
       }else{    

       if(token.nextToken().charAt(0)=='S'){ 
       } 
        outFile.print(token.nextToken()); 
        outFile.print("Shipping"); 
       } 
       } 
       } 

     } 
     } 
     readFile.close(); 
     outFile.close(); 

    } 



    } 
+0

每次你打电话'token.nextToken()'将返回你的下一个标记,然后前进到下一个标记可以再次调用。您可能只想在每次迭代中调用一次。 –

+0

是的,这是完全正确的。 –

回答

3

要调用token.nextToken()这么多次在你的while循环中。这就是让程序变得疯狂的原因。

你应该只使用一次,并把结果保存在临时变量,并使用它。

+0

我以为If语句只是检查条件?谢谢我会在这方面做更多工作。 –

+0

@HermesTrismegistus。是的,你只检查下一个令牌的条件。但是你阅读的不仅仅是这些。 –

+0

再次感谢我一起玩。 –

0

每次通话时间token.nextToken(),你得到的字符串,你切分中的下一个标记。所以在你的代码中,你在每个if语句中检查一个不同的字符串。你需要做的只是存储正确的标记并处理它。此外,您知道令牌生成器中的哪个令牌具有您想要的数据,因此不需要while循环,只需转到您想要的令牌。最后,你的if-else结构对我来说看起来很奇怪,所以我改变了它,除非我错过了我下面所做的更好的方式。所以像这样的东西替换while循环:

String thisToken; 

// the first token is the employee name so skip that one 
token.nextToken(); 
// save the next token as its the one we want to look at 
thisToken = token.nextToken(); 

outFile.print(thisToken); 

if(thisToken.charAt(0)=='A'){ 
    outFile.print(thisToken); 
    outFile.print("Accounting "); 

}else if(thisToken.charAt(0)=='H'){ 
    outFile.print(thisToken); 
    outFile.print("Human Resources "); 

}else if(thisToken.charAt(0)=='P'){ 
    outFile.print(thisToken); 
    outFile.print("Production "); 

}else if(thisToken.charAt(0)=='S'){ 
    outFile.print(thisToken); 
    outFile.print("Shipping"); 
} 
+0

你是!马虎,... hehehe ..冷酷的家伙......你称'.nextToken'两次。 –

+0

啊,是的,我看到,一个If/Else而不是嵌套if。这就说得通了。谢谢! –

+0

哈哈对不起,我提出了最后的答案,当它完成了一半...这应该解决您的问题 – Sloppy

相关问题