0

我理解没有这样的元素例外,但我不明白我做错了什么。我需要使用 Tokenizer,这样我才能读取诸如“A-902”或“S-823”之类的标记,并识别 0 处的字符以确定员工所在的部门。Information.txt 包含如下条目:

Jane Rivers, A-902, 05/16/2001, 1, 16.25
Bob Cox, S-823, 06/21/1990, 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();

    }



    }
4

2 回答 2

3

You are calling token.nextToken() so many times in your while loop. That is what making the program go crazy.

You should just use it once, and store the result in temporary variable, and use it.

于 2013-06-21T16:53:35.190 回答
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");
}
于 2013-06-21T17:05:41.197 回答