package zyntm;
import java.util.ArrayList;
import java.util.Scanner;
public class Users {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> stu = new ArrayList<String>();
ArrayList<Student> stu1 = new ArrayList<Student>();
int i = 0;
while(true){
String stuID = sc.next();
stu.add(stuID);
stu1.get(i) = new Student(stuID.substring(0, 4),stuID.substring(4, 6),stuID.substring(6, 8),stuID.substring(8, 10));
i++;
}
class Student {
String year;
String spe;
String class1;
String num;
Student(String year,String spe,String class1,String num){
this.year = year;
this.spe = spe;
this.class1 = class1;
this.num = num;
}
public String getYear() {
return year;
}
public String getSpe() {
return spe;
}
public String getClass1() {
return class1;
}
public String getNum() {
return num;
}
}
}
}
第十三行:怎么让Student类型的数组stu1调用下面的Student方法?
改为stu1.add()方法, 然后把类Student放到Users类外即可,因为如果Student类放到Users类内,则创建Students类对象之前,需要先创建其外部类Users对象。
修改如下:
参考链接:
package zyntm;
import java.util.ArrayList;
import java.util.Scanner;
public class Users {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> stu = new ArrayList<String>();
ArrayList<Student> stu1 = new ArrayList<Student>();
int i = 0;
while(true){
String stuID = sc.next();
stu.add(stuID);
// 使用Arrrays类的add方法,将创建的每个学生类对象添加到stu1中
stu1.add(new Student(stuID.substring(0, 4),stuID.substring(4, 6),stuID.substring(6, 8),stuID.substring(8, 10)));
// 打印根据输入信息创建的学生的相关信息
System.out.println("输入的信息为:"+stu1.get(i));
i++;
}
}
}
// 把学生类Student放到类Users类外
class Student {
String year;
String spe;
String class1;
String num;
Student(String year,String spe,String class1,String num){
this.year = year;
this.spe = spe;
this.class1 = class1;
this.num = num;
}
public String getYear() {
return year;
}
public String getSpe() {
return spe;
}
public String getClass1() {
return class1;
}
public String getNum() {
return num;
}
@Override
// 用于打印学生类的相关信息
public String toString() {
return "学生信息: [year=" + year + ", spe=" + spe + ", class1=" + class1 + ", num=" + num + "]";
}
}