ToString () Method Question

I worked on this assignemnt code here:

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 something like this:

Name: Wilson, Mary Ann
ID number: 12345
GPA: 3.5
+2


a source to share


4 answers


@Override
public String toString() {
    return "Name: " + getName() + "\n" +
            "ID Number: " + studentId + "\n" +
            "GPA: " + gpa;
}

      



+3


a source


Take a look at your getName method. You can use the same ideas (and actually getName) for toString. One may not know what \ n means a newline. So "foo \ nbar" is foo, then newline, then bar.



+2


a source


Just add this method.

public String toString() {
    // TODO: write code according requirements.
}

      

If your actual problem is more than you don't know how to do it, then you should be more specific in your question. You for example don't know how to insert newlines in String

? For this you can use \n

.

    return String.format(
        "Name: %s, %s\nID number: %d\nGPA: %f", fname, lname, studentId, gpa);

      


This suggests that the challenge is System#exit()

quite radical. Does enduser really have to restart the whole application for a simple input error?

+2


a source


public String toString() {
    String output = "Name: " + lname + ", " + fname + "\n" +
                  "ID number: " + studentId + "\n" +
                  "GPA: " + gpa + "\n";
    return output;
}

      

+2


a source







All Articles