Question

This was originally one line, but I wanted to format the percentage and when I replaced it, I got errors, so I did this instead (It displays how I like), but I was wondering what the correct way would be to do it? Hopefully, it will help me to understand why whatever I did before did not work.

System.out.print("\nThe "+oracleStock.name+"'s change is ");
System.out.printf("%3.2f",oracleStock.getChangePercent());
System.out.print("%");

Thank you for your help, :)

Was it helpful?

Solution

In printf, you can't use a % to represent %, because a % means that what follows is a field specifier. If you really want to put a % in your format, you use a double percent, like so:

System.out.printf("%nThe %s's change is %3.2f%%", oracleStock.name, oracleStock.getChangePercent());

By the way, instead of \n in printf, you should use %n because the latter will print the correct line separator depending on the platform.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top