简体   繁体   中英

Java scanner class storing multiple int values from datafile into an array

I am trying to create the below method to read the "studentmarks.txt" file. However, I cannot get students marks to be read as an int such as 65 60 52 and stored into an Array. It keeps outputing the error "java.util.InputMismatchException null". How would I go about fixing this without altering the format of the "studentmarks.txt" file? Thank you!

public void readMarksData(String fileName) throws FileNotFoundException
{


    File dataFile = new File(fileName);
    Scanner scanner = new Scanner(dataFile);

    String nameOfCohort = scanner.nextLine(); //1
    System.out.println(nameOfCohort);

    int noOfMarks = scanner.nextInt();  //2
    System.out.println(noOfMarks);

    scanner.nextLine();
    while( scanner.hasNext() )
    {

       scanner.useDelimiter("[,\n]");
       String name = scanner.next();      //3
       System.out.println(name);



         //            int marks[] = new int[3];
         //            for(int i = 0 ; i <= 3 ; i++)
         //            {
         //               marks[i] = scanner.nextInt();
         //            }

       int marks[] = new int[100];

       int markOne = scanner.nextInt();  //4 java.util.InputMismatchException null
       marks = new int[markOne];
       System.out.println(markOne);
       scanner.nextLine();



       int markTwo = scanner.nextInt();      //5
       marks = new int[markTwo];
       scanner.nextLine();

       int markThree = scanner.nextInt();      //6
       marks = new int[markThree];
       scanner.nextLine();
       //              
       //System.out.println(markOne + " " + markTwo + " " + markThree);

    }
    scanner.close();
}

studentmarks.txt:

CS1 Group 2
3
Andreas Antoniades
65 85 77
Charlotte Brocklebank
87 93 81
suzanne dawson
0 55 42

StudentRecord Class:

public class StudentRecord
{

   private String name;
   private String noOfMarks; 
   private int[] marks;

   public StudentRecord(String name)
   {
     marks = new int[24];
     this.name = name;  
   }
int result = Integer.parseInt(number);

您可以使用parseInt(String val)方法将 65 的字符串值解析为整数值并将其存储在数组中

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