0

First, thank you for spending some time on this problem. I've tried based on my own knowledge but can not find out where to modify. I have made a game and in the end, I have to return the formatted string to the terminal.

The exception appeared when I change basic string concatenation to the formatted string. I don't know how to fix it.

  1. players is the player array.
  2. WinRatio is score(int) divided by gamePlayed(int), rounding to integer.

Here is part of my code.

public static void searchAndPrintRankingDataDesc() {
    NimPlayer [] players = NimPlayer.getPlayer();
    Arrays.sort(players, Comparator.comparing((NimPlayer::getWinRatio)).reversed().thenComparing(NimPlayer::getUserName));
    Arrays.stream(players).forEach(System.out::println);

And my toString method:

public String getWinRatio() {
    return Integer.toString(Math.round(Float.valueOf(getScore())/ (getGamePlayed())*100));
}

public String toString() {
    return String.format( "%02d" +"% | "+ "%02d" +" games | "+ "%s " + "%s", getWinRatio(), gamePlayed, givenName, familyName);
}
Woden
  • 1,054
  • 2
  • 13
  • 26
  • Thanks, but there is another popped out for illegerConversion. And I change `getWinRatio` back to int type. Problem solved. Thanks @Renato – Woden Apr 27 '20 at 13:12

2 Answers2

2

% is a special character for String.format, to escape %, you will have to replace it with %%. So your statement becomes-

String.format( "%02d" +"%% | "+ "%02d" +" games | "+ "%s " + "%s", getWinRatio(), gamePlayed, givenName, familyName);
1

When using % in the formatted string, it has to be escaped using another %. And when formatting the integer value, it will get IllegalFormatConversionException if there has already a toString method.

This code here formatted the integer to string.

public String getWinRatio() {
return Integer.toString(Math.round(Float.valueOf(getScore())/ (getGamePlayed())*100));

}

And the code below formatted again, causing IllegalFormatConversionException.

public String toString() {
return String.format( "%02d" +"% | "+ "%02d" +" games | "+ "%s " + "%s", getWinRatio(), gamePlayed, givenName, familyName);

}

So, the answer will be:

public int getWinRatio() {
    return Math.round(Float.valueOf(getScore())/ (getGamePlayed())*100);
}
public String toString() {
    return String.format( "%02d" +"%%" + " | "+ "%02d" +" games | "+ "%s " + "%s", getWinRatio(), gamePlayed, givenName, familyName);
}
Woden
  • 1,054
  • 2
  • 13
  • 26