1

我正在尝试使用字符串标记器将数据从文件导入数组。

文件中的数据格式为

AA,BB,CC
AA,BB,CC

但我不断收到错误

Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
    at java.util.StringTokenizer.nextElement(StringTokenizer.java:407)
    at main.main(main.java:36)

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;


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

    Scanner input;
    String line;
    int x=0;
    String [] cName = new String [100];
    String [] cMascot = new String [100];
    String [] cAlias = new String [100];





         input = new Scanner(new File("test.txt"));

         while(input.hasNextLine()) {

             line = input.nextLine();
             StringTokenizer strings = new StringTokenizer(line,",");

             while (strings.hasMoreElements()) {
                 cName[x] = strings.nextElement().toString();
                 cMascot[x] = strings.nextElement().toString();
                 cAlias[x] = strings.nextElement().toString();
                 x++;
             }

         }


}

}

所以任何帮助将不胜感激。我不能使用数组列表,以便脱离上下文

4

3 回答 3

2

您不能在 while 语句中多次调用 .nextElement() ;在每个 .hasNextLine() 必须被调用

于 2013-05-25T13:10:43.953 回答
1

我建议你使用readLinesplit...

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

    String line;
    int x=0;
    String [] cName = new String [100];
    String [] cMascot = new String [100];
    String [] cAlias = new String [100];

    try (BufferedReader input = new BufferedReader(new FileStreamReader("test.txt"))) {

         while ((line = input.readLine())!=null) {

             cName[x] = line.split(",")[0];
             cMascot[x] = line.split(",")[1];
             cAlias[x] = line.split(",")[2];
             x++;
         }
    }

}
于 2013-05-25T13:10:15.613 回答
0

您也可以使用以下代码:

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

    Scanner input;
    String line;

    String cMascot = null;
    String cAlias = null;
    String cName = null;

    input = new Scanner(new File("test.txt"));
    while (input.hasNextLine()) {
        line = input.nextLine();
        StringTokenizer strings = new StringTokenizer(line, ",");

        while (strings.hasMoreElements()) {
            cName = strings.nextToken();
            cMascot = strings.nextToken();
            cAlias = strings.nextToken();
            System.out.println("cName :" + cName);
            System.out.println("cMascot :" + cMascot);
            System.out.println("cAlias :" + cAlias);
        }
    }

}
于 2013-05-25T15:09:00.103 回答