简体   繁体   中英

Split comma separated values in java, int and String

I have the following in a text file to import into an ArrayList:

Australia,2

Ghana,4

China,3

Spain,1

My ArrayList is made up of objects from another class, Team which has the fields TeamName and ranking. I can get the following to import the String and int into the team name, but I can't separate the number which is supposed to be the teams ranking:

  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");
    }

}

I'm guessing I have to use a split somewhere along the line, or convert a String to an integer??

Scanner.next() read the next token from input stream, and give String .

If you want to read the next integer, you should use nextInt() instead:

teams.setRanking(parser.nextInt());

Edit

You got InputMismatchException because by default, Scanner use java whitespace as delimeter.

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

In your case, the delimeter are comma , and new line \\n so you should config the delimeter for your scanner:

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

Another work around is to read the whole line and parse your line:

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

You can choose one of the two solutions above

Check out opencsv. It's 2018 and you shouldn't have to parse a text file yourself :).

By default scanner will use white space as delimiter

Override this by calling useDelimiter method in your case parser.useDelimiter(',');

Then for converting ranking string to int you parser.nextInt()

You can code something like below to suite your purpose. You have two tokens in your use case ie comma (,) and new line (\\n). As a result, next() can't be used in a straight forward way.

I am going over each line, then tokenizing each line on comma and finally getting subsequent tokens.

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]); 
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM