2

I'm making a list of strings in a TreeMap to keep track of grades for a bunch of students. Right now my program is printing the list of strings like this:

Jimmy: C+
Tim: A
Samantha: B-
Mike: A-

When I want it to print out like this:

Jimmy:    C+
Tim:      A
Samantha: B-
Mike:     A-

How do I get the names and grades to be spaced like this? Here's the section of my code that prints out everything:

//Print all students with their grades
case "P": System.out.println();
          for(Map.Entry<String, String> entry : grades.entrySet())
          {
             System.out.println(entry.getKey() + ":  " + entry.getValue());
          }
          System.out.println();
          break;
Joey Flynn
  • 33
  • 3

4 Answers4

3

The simplest solution is probably using a tab character instead of spaces in your print statement.

System.out.println(entry.getKey() + ":\t" + entry.getValue());

Another way to do it is using the String format method to right-pad the student's name with spaces. The following code will print a student's name in a column 10 characters wide. This will be more reliable if you know the maximum length of names before printing the report (which you should be able to find easily).

String name = "Tim:";
String student = String.format("%1$-10s", name);
System.out.println(student + "A");
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
0

You can look at option of using System.out.format with different format options like right justifying out etc. Just google this. Here is one link you an look at

Saurabh
  • 7,703
  • 2
  • 20
  • 29
0

You want to left-pad the strings. Check out this answer: How can I pad a String in Java?

You also might want a function to calculate the maximum length of all the names you're trying to output. Something like.

private int maxLength(Collection<String> names) {
        int max = 0;
        for (String s : names) {
            if (s.length() > max) {
                max = s.length();
            }
        }
        return max;
    }

Then, use it like this: maxLength(grades.keySet());

Community
  • 1
  • 1
JohnnyK
  • 1,093
  • 6
  • 10
0

Input this to the System.out.println() in your loop:

String.format("%-10s %s", entry.getKey()+":", entry.getValue());
Sami N
  • 1,124
  • 2
  • 9
  • 21