How to format multiline tostring() using printf in Java

Therefore, for my beginner programming class, we must write a program focusing on inheritance. We can create and input information for different types of college students

I have programs and output that work normally, but my professor wants us to format the output as follows:

When entering new student information, he wants to use the toString () method to print the student information neatly, as shown below:

Selection: Student Name: student card: number of points:

But at the end of the program, he wants us to format the output with printf so that it looks like this:

Student type: (tag) student name: (tag) student ID: (tag) number of points: (TAB) different information based on student type: (tag) tuition:

This is the code of my original toString () method in the student superclass. The subgrad and grad subclasses just call it and add their specific properties to the end:

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

This is the code in the test class. I try to format:

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 is just a tab in the name line of the toString () method and tuition output My professor wants us to use printf, but I don't know how to apply it to all three lines of the toString () method I can't edit the toString () method itself because it will screw up the format of the non - Final printout What on earth did I do wrong?

Solution

You simply add the tab to the return string:

return "\tStudent Name: " + getName() + "\n" + "\tStudent ID: " + getId() + "\n" + "\tNumber of Credits: " + getNumCredits();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>