Java: reading a text file and storing information in an array using a scanner class

I have a text file that includes student classes, such as:

Kim $ 40 $ 45
Jack $ 35 $ 40

I am trying to read this data from a text file and store the information in a list of arrays using the scanner class. Can someone help me write the code correctly?

The 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)
+3
source share
2 answers

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

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

Your problems are as follows:

  • You mistakenly read the whole line to get the student name
  • $ - metacharacter of regular expressions to be escaped
  • You need to provide both line separators and field separators.
+2

while .

nextLine() , , . nextInt() , int. .
, , :

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

; , .

, StringTokenizer .

0

Source: https://habr.com/ru/post/1736830/


All Articles