以逗号分隔的文本文件到数组

时间:2019-03-10 08:22:09

标签: java arrays separator

我有一个多行文本文件,每行3个逗号分隔的条目。

示例:

  

苏联,Larisa_LATYNINA,18
  美国,Michael_PHELPS,16
  苏联,Nikolay_ANDRIANOV,15

我正尝试将它们分成3个阵列,其中1个代表国家,1个代表人,1个代表奖牌。

        ArrayList<String> country = new ArrayList<>();
        ArrayList<String> name = new ArrayList<>();
        ArrayList<Integer> medals = new ArrayList<>();
        java.io.File file = new java.io.File("Olympics.txt");
        Scanner input = new Scanner(file);
        input.useDelimiter(" , ");
        while(input.hasNext()) {
            country.add(input.next());
            name.add(input.next());
            medals.add(input.nextInt());
        }

但是每次尝试运行它时都会出错。我不确定如何将文件中的每个“列”分成各自的数组。

如果我使用useDelimiter(",");而不是useDelimiter(" , ");,则会收到以下异常:

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at OlympicWinners.main(OlympicWinners.java:14)

这是我得到的错误。第14行是

Medals.add(input.nextInt());

3 个答案:

答案 0 :(得分:1)

根据您的文本示例,定界符不是用空格(" , ")包围的逗号,而是逗号(",")。删除那些空格,您就可以了:

input.useDelimiter(",");

答案 1 :(得分:0)

由于最后一行protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view); fragment = new MapsActivity(); FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.activity_fragment_view, fragment); ft.commit(); 返回

,您得到InputMismatchException
input.nextInt()

由于"18 United States" ,之间没有18分隔符(但是有行分隔符United States),所以每个标记都从分隔符返回到分隔符。

您应该从文件中读取所有行,并用分隔符将其分开:

\n

答案 2 :(得分:0)

请为此修改您的代码:

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        ArrayList<String> country = new ArrayList<>();
        ArrayList<String> name = new ArrayList<>();
        ArrayList<Integer> medals = new ArrayList<>();
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader("F://test.txt"));
            String line = reader.readLine();
            while (line != null) {
                String[] lineParts = line.split(",");
                country.add(lineParts[0]);
                name.add(lineParts[1]); 
                medals.add(Integer.valueOf(lineParts[2]));
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(country);
        System.out.println(name);
        System.out.println(medals);

    }

}

在test.xml中:

Soviet Union,Larisa_LATYNINA,18
United States,Michael_PHELPS,16
Soviet Union,Nikolay_ANDRIANOV,15

代码输出:

[Soviet Union, United States, Soviet Union]
[Larisa_LATYNINA, Michael_PHELPS, Nikolay_ANDRIANOV]
[18, 16, 15]