在java,int和String中拆分逗号分隔值

时间:2018-05-05 04:32:49

标签: java arraylist split

我在文本文件中有以下内容要导入到ArrayList:

澳大利亚,2

加纳,4

中国,3

西班牙,1

我的ArrayList由来自另一个类Team的对象组成,其中包含TeamName和ranking字段。我可以得到以下内容将String和int导入到团队名称中,但是我不能将应该是团队排名的数字分开:

  public void fileReader()
  {
    try
    {
        String filename = "teams.txt";
        FileReader inputFile = new FileReader(filename);
        Scanner parser = new Scanner(inputFile);

        for (Team teams : teams)
        {                 
            teams.setTeamName(parser.next());
            teams.setRanking(parser.next()); //this doesn't work
        }
    }

    catch (IOException e)
    {
        System.out.println("Cannot find file");
    }

}

我猜我必须在线上某处使用拆分,或者将String转换为整数?

4 个答案:

答案 0 :(得分:0)

Scanner.next()从输入流中读取下一个标记,并提供String

如果您想阅读下一个整数,则应使用nextInt()代替:

teams.setRanking(parser.nextInt());

修改

你得到了InputMismatchException,因为默认情况下,Scanner使用java空格作为分隔符。

WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+")

在您的情况下,分隔符为逗号,和新行\n,因此您应为扫描仪配置分隔符:

Scanner parser = new Scanner(inputFile);
s.useDelimiter(",|\\n")

另一种解决方法是阅读整行并解析你的行:

String line = parse.nextLine();
String[] parts = line.split(",");
team.setTeamName(parts[0]);
team.setRanking(Integer.parse(parts[1]));

您可以选择以上两种解决方案之一

答案 1 :(得分:0)

查看opencsv。它是2018年,你不应该自己解析一个文本文件:)。

答案 2 :(得分:0)

默认情况下,扫描仪将使用空格作为分隔符

通过在案例解析器中调用useDelimiter方法来覆盖它.useDelimiter(',');

然后,为了将排名字符串转换为int,您需要解析.nextInt()

答案 3 :(得分:0)

您可以编写类似下面的内容来满足您的目的。 您的用例中有两个令牌,即逗号(,)和新行(\ n)。因此,next()不能以直接的方式使用。

我要越过每一行,然后用逗号标记每一行,最后得到后续的标记。

try
    {
        String filename = "teams.txt";
        FileReader inputFile = new FileReader(filename);
        Scanner parser = new Scanner(inputFile);

        for (Team teams : teams)
        {   
            String[] splitLine = sc.nextLine().split(","); // comma delimited array

            teams.setTeamName(splitLine[0]);
            teams.setRanking(splitLine[1]); 
        }
    }