![](/img/trans.png)
[英]How do I easily and neatly print multiple objects using a toString method, that are also aligned?
[英]How do I print using toString using inheritance in Java
public class StuTest2
{
public static final int NUMBER_OF_STUDENTS = 7;
public static void main(String[] args)
{
Student[] stus = new Student[NUMBER_OF_STUDENTS];
// Student has ID, name, and GPA
stus[0] = new Student(123, "Suzy", 3.9);
// Default for missing GPA will be 9.99 "special value
stus[1] = new Student(234, "Tom");
// Default name will be "Student #xxx" where
// "xxx" is the actual ID number
stus[2] = new Student(456);
// A grad student also has a thesis topic
stus[3] = new GradStudent(567, "Fred", 3.8, "Java");
// Default thesis topic is "Undecided"
stus[4] = new GradStudent(678, "Staci", 3.1);
// Doctoral students earn a stipend
stus[5] = new DoctoralStudent(789, "Mandy", 4.0, "Databases", 3550.00);
// If missing, the default stipend is $3000.00
stus[6] = new DoctoralStudent(890, "Ned", 3.7, "Cisco Networking");
// Inside the loop, the toString method is called for each
// student. All graduate students show the word "Graduate" in
// front of the output from this method.
for(Student stu : stus)
{
}
}
}
class Student
{
private int id;
private String name;
private double gpa;
public Student(int i, String n, double g)
{
id = i;
name = n;
gpa = g;
}
public Student(int i)
{
this(i, "Student #" + i);
}
public Student(int i, String n)
{
this(i, n, 9.99);
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public double getGPA()
{
return gpa;
}
public String toString()
{
return System.out.println(stus.getId+", " + stus.getName
+ ", " + stus.getGPA);
}
}
class GradStudent extends Student
{
private String topic;
public GradStudent(int i, String n, double g, String t)
{
super(i, n, g);
topic = t;
}
public GradStudent(int i, String n, double g)
{
this(i, n, g, "Undecided");
}
public String getTopic()
{
return topic;
}
public String toString()
{
return super.getTopic();
}
}
class DoctoralStudent extends GradStudent
{
private double stip;
public DoctoralStudent(int i, String n, double g, String t, double s)
{
super(i, n, g, t);
stip = s;
}
public DoctoralStudent(int i, String n, double g, String t)
{
this(i, n, g, t, 3000.00);
}
public double getStip()
{
return stip;
}
public String toString()
{
return super.getStip();
}
}
我正在尝试使用return super.toString()进行打印,但是我发现错误提示无法找到stus的符号,但是我在开始学生课程之前就拥有了它。 是什么赋予了? ps,对不起,结账不好,尝试达到这里的标准,哈哈
您的“ stus”变量仅在 main()方法内部,因此您不能在该方法之外访问它。 此外,“ stus”是一个数组,因此在其上调用getId甚至都没有意义。 此外,请注意,getId引用变量,因为它后面没有括号。
请记住,在您的toString()方法中,您已经在“学生对象”内部,因此您可以直接调用getId()函数:
public String toString()
{
return getId() +", " + getName() + ", " + getGPA();
}
还要注意,我已经在您的toString方法中删除了System.out.println()函数,因为它不返回任何内容,因此无论如何都没有意义。
您的代码中有很多不正确的语法,我强烈建议从小得多的角度开始。 如果逐步开发程序,而不是一口气完成全部工作,那么运气会更好。 我建议从头开始,对添加的每一行进行编译和测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.