0

我看到你不能在数组上使用字符串标记器,因为你不能转换String()String[]. 一段时间后,我意识到如果 inputFromFile 方法逐行读取它,我可以逐行标记它。我只是不知道该怎么做才能返回它的标记化版本。

我假设line=in.ReadLine();我应该把StringTokenizer token = new StringTokenizer(line,",")..放在行中,但它似乎不起作用。

有什么帮助吗?(我必须标记逗号)。

public class Project1 {

    private static int inputFromFile(String filename, String[] wordArray) {
        TextFileInput in = new TextFileInput(filename);
        int lengthFilled = 0;
        String line = in.readLine();
        while (lengthFilled < wordArray.length && line != null) {
            wordArray[lengthFilled++] = line;
            line = in.readLine();
        }// while
        if (line != null) {
            System.out.println("File contains too many Strings.");
            System.out.println("This program can process only "
                    + wordArray.length + " Strings.");
            System.exit(1);
        } // if
        in.close();
        return lengthFilled;
    } // method inputFromFile

    public static void main(String[] args) {
        String[] numArray = new String[100];
        inputFromFile("input1.txt", numArray);
        for (int i = 0; i < numArray.length; i++) {
            if (numArray[i] == null) {
                break;
            }
            System.out.println(numArray[i]);
        }// for

        for (int i=0;i<numArray.length;i++)
        {
            Integer.parseInt(numArray[i]);
        }

    }// main
}// project1
4

1 回答 1

0

这就是我的意思:

while (lengthFilled < wordArray.length && line != null) {
            String[] tokens = line.split(",");
            if(tokens == null || tokens.length == 0) {
                 //line without required token, add whole line as it is
                 wordArray[lengthFilled++] = line;
            } else {
                 //add each token into wordArray
                 for(int i=0; i<tokens.length;i++) {
                     wordArray[lengthFilled++] = tokens[i];
                 }
            }

            line = in.readLine();
}// while

也可以有其他方法。例如,您可以使用 StringBuilder 将所有内容读取为一个大字符串,然后将其拆分为所需的标记等。上述逻辑只是为您指明正确的方向。

于 2012-12-17T03:46:45.393 回答