没有这样的元素例外

时间:2013-06-21 16:51:38

标签: java tokenize

我理解没有这样的元素异常,但我不明白我做错了什么。我需要使用Tokenizer,因此我可以读取诸如“A-902”或“S-823”之类的标记,并将字符标识为0以确定该员工所在的部门.Information.txt包含以下条目:< / p> Jane Rivers,A-902,05 / 16 / 2001,1,15.25
Bob Cox,S-823,06/21 / 1990,2,15.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();

    }



    }

2 个答案:

答案 0 :(得分:3)

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

您应该只使用一次,并将结果存储在临时变量中,然后使用它。

答案 1 :(得分:0)

每次调用token.nextToken()时,都会获得标记的字符串中的下一个标记。因此,在您的代码中,您将检查每个if语句中的不同字符串。您需要做的只是存储正确的令牌并处理它。此外,您知道tokenizer中的哪个令牌具有您想要的数据,因此不需要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");
}