First, I apologize if something like this has been answered already. I tried to search for any questions like this but I didn't find anything similar (at least with the keywords I used). Please moderate this as needed! It's my first post on the site.
I'm practicing String.format in Java and having trouble with making the elements of my 'Name' column all the same width. I'm using JDK 9 if that's relevant at all. In my code below, the issue in question is within the for-loop block. I'm taking the first and last names from their respective String arrays. I know I can solve my problem if I made each full name into one String, but for the sake of this exercise and in order to further my Java skills, I'd like to know if there is a solution to this problem. Thank you :)
public static void grades() {
Random rand = new Random();
// final grade is calculated based on points achieved out of 45. Rounded to 1 decimal
String[] rosterFirst = {"Harry", "Seamus", "Dean", "Neville", "Ron", "Dennis"};
String[] rosterLast = {"Potter", "Finnegan", "Thomas", "Longbottom", "Weasley", "Creevey"};
System.out.println("2018 Hogwarts Graduating Class Scores \n" +
String.format("%2$-25s %1$-12s", "Grade", "Name"));
for (int i = 0; i < rosterFirst.length; i++) {
double finalGrade = (25 + rand.nextDouble() * 20) / 45 * 100;
System.out.println(String.format("%s, %-15s %-12.1f", rosterLast[i], rosterFirst[i], finalGrade));
}
}
Output:
2018 Hogwarts Graduating Class Scores
Name Grade
Potter, Harry 70.3
Finnegan, Seamus 75.9
Thomas, Dean 96.9
Longbottom, Neville 98.2
Weasley, Ron 58.7
Creevey, Dennis 76.0
(Not sure if code output is wrongly formatted in this post. Please correct me if it is)