tags:

views:

89

answers:

4

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

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

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.

Matthew Flaschen
+2  A: 

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?

BalusC
Actually it exits regardless.
Matthew Flaschen
@Matthew: how do you know that?
BalusC
Since the `System.exit` is outside the conditional.
Matthew Flaschen
@Matthew: I hate braceless `if-else` blocks.
BalusC
+2  A: 
public String toString() {
    String output = "Name: " + lname + ", " + fname + "\n" +
                  "ID number: " + studentId + "\n" +
                  "GPA: " + gpa + "\n";
    return output;
}
Chris J
+3  A: 
@Override
public String toString() {
    return "Name: " + getName() + "\n" +
            "ID Number: " + studentId + "\n" +
            "GPA: " + gpa;
}
PortableWorld
Thank you very much!