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

So, for my beginner programming class, we needed to write an inheritance-oriented program where we could create and enter information for different students.

I have a program, and the output works fine, but my professor wants us to format the output like this:

When entering new student information, he wants the student information to be printed accurately using the toString () method, like this:

Choices:
Student Name : Student
ID:
Number of Credits:

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

Student type:
(tab) Student name:
(tab) Student ID:
(tab) Number of credits:
(tab) Miscellaneous information by student type:
(Tab) Education:

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

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 am trying to format this:

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, these are only tabs in the string name of the toString () method and output for training. 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 cannot edit the toString () method because this would ruin the formatting of the unconfigured printouts. What am I doing wrong?

+4
2

:

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

, Student , Student . toString Student StudentPrinter, : printFinal printNonFinal. Student .

. .

0

Source: https://habr.com/ru/post/1659673/


All Articles