Skip to content
Advertisement

Required to calculate the number of minutes as an int, then the seconds as a double. method should use a format string in Java

I am in the process of creating a public method String toString().

The requirement is to take a randomly generated number which is tenths of seconds (for example 6500) and convert these into int minutes and double seconds.

I need to use this format string: "%s t %d mins %.1f secs t %s".

I am struggling to get my head round this as I have created the following method:

public String toString()
   {
      int time = 6500;
      int minutes = time / 600;
      double seconds = (time % 600) / 600;
      String displayTime = String.format("%s t %d mins" + minutes, seconds  + "%.1f secs t %s");

return this.getName() + ", " + displayTime;
    }

I am receiving an error:

java.util.MissingFormatArgumentException: Format specifier 'd'

It would need to return the below:

John Doe 19 mins 8.2 secs

I am new to this site and Java, so any help is extremely helpful.

Advertisement

Answer

You need to change your code, especially this line:

String displayTime = String.format("%s t %d mins" + minutes, seconds  + "%.1f secs t %s");

to:

String name = getName(); //to get the string "John Doe"
String displayTime = String.format("%s t %d mins %.1f secs t", name, mins, seconds);

return name + "," + displayName; //we already have the name defined

For this to work, the variable names should be at the end and not in the middle. Also, the number of “%”‘s in your string should be equal to the variable. For example, the first %s in my answer above is for the name, the next %d is for the minutes, and the last %.1f is for the seconds upto one decimal point.

You should use this link to help you understand this concept more: https://www.javatpoint.com/java-string-format

Feel free to ask me in the comments if my answer doesn’t make sense.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement