Dominic Oryema
Dominic Oryema

Reputation: 25

Java String format error

for some reason this string format is not working. It says that frameCount should be an object. I'm not importing any libraries at the moment. Does anyone know why it gives an error?

frameRate is a String, frameCount is an int

frameRate = String.format("FPS %s", frameCount);

Upvotes: 0

Views: 6449

Answers (6)

Jens
Jens

Reputation: 69440

use: frameRate = String.format("FPS %d", frameCount);

%d stands for a digit %s is a String

Read the documentation about Formatter for more informations.

Upvotes: 0

Ninad Pingale
Ninad Pingale

Reputation: 7069

If you need to keep frameCount as an integer (because of requirement), you can convert it to string, but this will unnecessarily increase one step and code performance will be degraded.

frameRate = String.format("FPS %s", String.valueOf(frameCount)); 

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

More than likely you're using an old version of Java (pre-1.5) where parameters were not automatically autoboxed. Correcting the format specifier, you could use

frameRate = String.format("FPS %d", frameCount);

Upvotes: 0

tmarwen
tmarwen

Reputation: 16354

Either use the appropriate placehodler for int primitives which is %d:

frameRate = String.format("FPS %d", frameCount);

Or keep the current formatting rule and convert the int frameCount to a String to fit in the %s placeholder:

frameRate = String.format("FPS %s", String.valueOf(frameCount)); //Useless overhead

Upvotes: 0

Adrian Toma
Adrian Toma

Reputation: 547

Maybe try to print an int? Instead of :

frameRate = String.format("FPS %s", frameCount);

Change it to:

frameRate = String.format("FPS %d", frameCount);

Upvotes: 0

Lukas Eichler
Lukas Eichler

Reputation: 5903

%s is the placeholder for a String use %d instead.

String.format() is also the slowest way to build Strings. Use a Stringbuilder or for simple cases just the + operator.

frameRate = "FPS " + frameCount;

Upvotes: 2

Related Questions