0

I want to ask what the "%" + something + "" does in java? And can't we just use "=" instead of replacing " " with "="?

bar = String.format("%" + percentage +"s", " ").replace(" ", "=")

2 Answers 2

1

Yes. It is possible to write directly like this.

bar = String.format("%" + percentage +"s", "=");
Sign up to request clarification or add additional context in comments.

Comments

0

That depends a bit on what percentage is; if it is (as I assume) an int, your code just prints "=" to the screen "percentage" times

int percentage = 20;
System.out.println(String.format("%" + percentage +"s", " ").replace(" ", "="));
//prints ====================

If that is the intention, you can't just leave the replace part out - or more specifically: it won't give you the same result:

System.out.println(String.format("%" + percentage +"s", "="));
//prints                    =

Explanation:

The format("%" + percentage +"s", ...) brings the second parameter to the length you have given (in this case percentage). If the length is shorter than the second parameter, it will add spaces on the left until the desired length is reached.

The first version uses that as a "trick" and replaces the spaces generated afterwards with a "=".

The second version just says: take this "=" and add spaces on the left until it has reached the desired length.

3 Comments

hmm, so why the second code will not give me the same result? I want to print percentage times of "=“
I have added some more explanation.
If that solves your problem, could you please accept the answer to close the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.