简体   繁体   中英

How to format a multi-line toString() using printf in Java

So for my beginners programming class we had to code a program focusing on inheritance where we could create and enter information for different kinds of college students.

I have the program and the output working just fine, but my professor wants us to format the output like so:

When entering a new student information, he wants a student's info to be printed out neatly using a toString() method like this:

Choice:
Student Name:
Student ID:
Number of Credits:

However at the end of the program, he wants us to format the output using printf so that it looks like so:

Type of Student:
(tab)Student Name:
(tab)Student ID:
(tab)Number of Credits:
(tab)Different info based on type of student:
(tab)Tuition:

Here is my code for the original toString() method in the student superclass, the Undergrad and Grad subclasses just call this and then add on their specific attributes to the end:

public String toString()
{
  return "Student Name: " + getName() + "\n" + "Student ID: " + getId() + "\n" + "Number of Credits: " + getNumCredits();
}

And here is the code in the test class where I try to format that:

for(Student s: enrollment)
  {
     if(s instanceof Undergrad)
     {
        System.out.printf("Undergraduate Student: ");
        System.out.printf("%n\t" + s.toString());
        System.out.printf("%n\tTuition: " + s.calcTuition());
        System.out.printf("%n");
     }
     else
     {
        System.out.printf("%nGraduate Student: ");
        System.out.printf("%n\t" + s.toString());
        System.out.printf("%n\tTuition: " + s.calcTuition());
        System.out.printf("%n");
     }
  }            

However, this only tabs in the Name line of the toString() method and Tuition output. My professor wants us to use printf for this but I'm not sure how to make it apply to all three lines of the toString() method. I can't edit the toString() method itself because that would screw up the formatting of the non-final printouts. What am I doing wrong?

您只需将选项卡添加到返回字符串:

return "\tStudent Name: " + getName() + "\n" + "\tStudent ID: " + getId() + "\n" + "\tNumber of Credits: " + getNumCredits();

You're struggling with the fact, that your Student class has too many responsibilities, namely knowing the Student's properties and formatting output for two different cases. Instead of defining toString inside Student, try to define a different class StudentPrinter that provides two methods: printFinal and printNonFinal . Both take an object of type Student and provide the needed output.

See also the Single Responsibility Principle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM