java: Read text file and store the info in an array using scanner class

只愿长相守 提交于 2019-12-14 00:33:55

问题


I have a text file include Student Grades like:

Kim $ 40 $ 45
Jack $ 35 $ 40

I'm trying to read this data from the text file and store the information into an array list using Scanner Class. Could any one guide me to write the code correctly?

Code

import java.io.*;
import java.util.*;

public class ReadStudentsGrade {

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

    ArrayList stuRec = new ArrayList();
    File file = new File("c:\\StudentGrade.txt");
    try {
        Scanner scanner = new Scanner(file).useDelimiter("$");

        while (scanner.hasNextLine())
        {
            String stuName = scanner.nextLine();
            int midTirmGrade = scanner.nextInt();
            int finalGrade = scanner.nextInt();
            System.out.println(stuName + " " + midTirmGrade + " " + finalGrade);
        }
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

Runtime error:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at writereadstudentsgrade.ReadStudentsGrade.main(ReadStudentsGrade.java:26)

回答1:


Try useDelimiter(" \\$ |[\\r\\n]+");

        String stuName = scanner.next(); // not nextLine()!
        int midTirmGrade = scanner.nextInt();
        int finalGrade = scanner.nextInt();

Your problems were that:

  • You mistakenly read whole line to get student name
  • $ is a regex metacharacter that needs to be escaped
  • You need to provide both line delimiters and field delimiters



回答2:


Your while loop is off.

nextLine() will get you all what's left of the line and advance the cursor to there. nextInt() will then jump delimiters until it finds an int. The result will be skipping of values.
Assuming Kim and Jack were on different lines you would get:

stuName == "Kim $ 40 $ 45"
midTirmGrade == 35
finalGrade == 40

as your output; which isn't what you want.

Either you need to use the end-of-line as the delimiter or use a StringTokenizer to break each line up and then parse each of the sections as individual tokens.



来源:https://stackoverflow.com/questions/2440103/java-read-text-file-and-store-the-info-in-an-array-using-scanner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!