class studentadd public static void add ListStudent add = ArraysasList; Scanner sc = new ScannerSystemin; Systemoutprintln请输入学生姓名; String name = scnext; Systemo
在您提供的代码中,您定义了一个空的List对象add,然后试图在循环中访问其中的元素并调用get方法。但是,由于add列表是空的,因此循环根本不会执行。
另外,您使用了Arrays.asList()来创建一个不可变的列表,因此您不能在之后向其添加新的元素。
要解决这个问题,您可以修改代码如下:
public static void add() {
List<Student> students = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生姓名");
String name = sc.next();
System.out.println("请输入学生年龄");
int age = sc.nextInt();
System.out.println("请输入学生性别");
String sex = sc.next();
System.out.println("请输入学生学号");
int id = sc.nextInt();
System.out.println("请输入学生成绩");
int grade = sc.nextInt();
Student student = new Student(name, age, sex, grade, id);
students.add(student);
System.out.println("添加成功");
}
在这个修改后的代码中,我们创建了一个可变的ArrayList对象students,并向其中添加了一个新的Student对象。这样,您就可以成功添加学生信息了
原文地址: http://www.cveoy.top/t/topic/iv5V 著作权归作者所有。请勿转载和采集!