gpt4 book ai didi

java - 扫描文件并将其分配给对象数组时获取 "Mismatch error"

转载 作者:行者123 更新时间:2023-12-02 05:46:11 24 4
gpt4 key购买 nike

给定一个学生花名册文件,其中第一行是类(class)中的学生人数,在接下来的几行中,我提供了他们的姓名、ID 和年龄,如下所示:

    5
Mary, 1010, 15
Ben, 1119, 16
Sam, 2278, 15
Alex, 3245, 15
Mia, 4448, 16

我应该创建一个学生对象数组,但当我尝试编译代码时收到“不匹配错误”。

我已经尝试了以下方法,但我不确定我的代码有什么问题。

public class Classroom_Runner{
public static void main(String[] args)throws Exception{

File roster = new File("info.txt");
Scanner scanFile = new Scanner(roster);
Scanner scanInput = new Scanner(System.in);
//roster.split(", ");

//String insideFile = "";
int sizeClass = 0;
Classroom[] Students = new Classroom[0];

while(scanFile.hasNext()){
sizeClass =scanFile.nextInt();
String name = scanFile.next(); //<-- This would be line 35
int ID = scanFile.nextInt();
int age = scanFile.nextInt();

Classroom student = new Classroom( name, age, ID);

}
for(int i = 0; i<Students.length;i++){
System.out.println(Students[i]);}
}
}

实际输出是:

    Exception in thread "main" java.util.InputMismatchException
at Classroom_Runner.main(Classroom_Runner.java:35)

但预期输出应该是:

    Mary, 1010, 15
Ben, 1119, 16
Sam, 2278, 15
Alex, 3245, 15
Mia, 4448, 16

最佳答案

        sizeClass =scanFile.nextInt();
String name = scanFile.next();

String temp = scanFile.next();
temp = temp.substring(0, temp.length() -1);

int realID = Integer.parseInt(temp);

//rest of your code

您应该去掉结尾的逗号,以便以正确的格式捕获整数。

关于java - 扫描文件并将其分配给对象数组时获取 "Mismatch error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com