toString() Method question
I've been working on this assignemnt here's code:
public class Student
{
private String fname;
private String lname;
private String studentId;
private double gpa;
public Student(String studentFname,String studentLname,String stuId,double studentGpa)
{
fname = studentFname;
lname = studentLname;
studentId = stuId;
gpa = studentGpa;
}
public double getGpa()
{
return gpa;
}
public String getStudentId()
{
return studentId;
}
public String getName()
{
return lname + ", " + fname;
}
public void setGpa(double gpaReplacement)
{
if (gpaReplacement >= 0.0 && gpaReplacement <= 4.0)
gpa = gpaReplacement;
else
System.out.println("Invalid GPA! Please try again.");
System.exit(0);
}
}
Now I need to create a toString() method that returns a String formatted s开发者_开发知识库omething like this:
Name: Wilson, Mary Ann ID number: 12345 GPA: 3.5
@Override
public String toString() {
return "Name: " + getName() + "\n" +
"ID Number: " + studentId + "\n" +
"GPA: " + gpa;
}
Look at your getName method. You can use the same ideas (and actually getName itself) for the toString. One thing you may not know is that \n means newline. So "foo\nbar" is foo then a newline, then bar.
Just add that method.
public String toString() {
// TODO: write code according requirements.
}
If your actual problem is more that you don't know how to do that, then you should be more specific in your question. Do you for example not know how to insert newlines in a String
? Well, you can use \n
for that.
return String.format(
"Name: %s, %s\nID number: %d\nGPA: %f", fname, lname, studentId, gpa);
That said, that System#exit()
call is pretty drastically. Does the enduser really have to restart the entire application for a simple input error?
public String toString() {
String output = "Name: " + lname + ", " + fname + "\n" +
"ID number: " + studentId + "\n" +
"GPA: " + gpa + "\n";
return output;
}
精彩评论