java string format, replace "" - java

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(" ", "=")

Yes. It is possible to write directly like this.
bar = String.format("%" + percentage +"s", "=");

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.

Related

Why printing "" + variables output each variable individually without spacing?

One of my assignments has this code:
System.out.println("" + x + y + count);
that outputs the value of x, y and count individually without any spaces. I would like to know more about it online. However, I can't seem to find the right keywords to search it up online. Can someone please explain to me the logic behind this or perhaps point to me a name or keyword for such a situation?
I have always known the " " as a tool to print out a string so I'm confused by this.
Thanks in advance.
If we apply standard Java precedence rules, the statement:
System.out.println("" + x + y + count);
is equivalent to
System.out.println((("" + x) + y) + count);
Then we look at the meaning of +
If the static types of both a and b are numeric types (either primitive numeric or their boxed types) then a + b is numeric addition.
Otherwise, a + b is string concatenation. The two arguments are converted to strings and the strings are concatenated.
Based on this we can say that all of the + operators in the example will be treated as string concatenations.
If you want spaces between x, y and count you need to add some string literals; e.g.
System.out.println("" + x + " " + y + " " + count);
or, more simply:
System.out.println(x + " " + y + " " + count);
If you wanted x, y and count to be added (assuming that they are numeric), then you could write this:
System.out.println("" + (x + y + count));
or, more simply:
System.out.println(x + y + count);
The latter is using a different overload of println.
I have always known the "" as a tool to print out a string so I'm confused by this.
Ummm ... it is actually an empty string literal. The usage "" + x is simply an idiom for converting x to a String. The empty string literal has other uses too. The main one is to represent a String with zero characters.
Or you can use String format like this:
System.out.printf("%d%d%d", x, y, count);
The "" is an empty String. In Java when you concatenate a String with other primitives that can be cast to String the result is a String. That means that the code
System.out.println("" + something);
is a different way to write
System.out.println(String.valueOf(something));
However in your scenario the "" + x + y + count means that the elements are converted to String and then concatenated - this means that if x==1, y==2, count==3 the result would be 123. If you wanted to just cast the result to String you would have to indicate that the computation should happen before casting to String for example by using brackets
System.out.println("" + (x+y+count));
The output of this would be 6.

Strange result when trying to add a char after an integer and then print the result

I'm trying to create a simple calculator voor Ohm's law.
So the idea is that you can fill in 2 variables and then it will calculate the third variable.
When I was creating this program, I found a little problem and I don't understand how it happens and unfortunately I'm not able to find the answer.
I tried to print a String where the complete calculation is shown. So the 2 variables the user filled in and the answer. After the variable for Ohm ('R' in this example) the correct symbol should be printed aswell.
As shown in the example below, the only way I can add the symbol after the variable is by first adding an empty string(""). Otherwise the unicode wil be added to the variable?!
I've made a quick example to show my problem:
public class Main {
public static void main(String[] args) {
float R = 2.54f;
float U = 4.00f;
float I = R / U;
char ohm = '\u2126';
System.out.println(R + "" + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");
System.out.println(R + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");
}
}
Result in console:
2.54Ω (R) / 4.0V (U) = 0.635A (I)
8488.54 (R) / 4.0V (U) = 0.635A (I)
As you can see, the second print doesn't show the Ohm symbol, but adds a value to the variable 'R'. Hopefully I've made my question clear enough.
Thanks in advance.
R + ohm performs a numeric addition of a float and a char (which is an integral type). Therefore you see a float result instead of the String concatenation you expect. The float result you see is 8486 + 2.54 (since 8486 is the decimal value of the hexadecimal number 2126).
In your first println statement you avoid that by concatenating a String ("") to the float, which results in a String. Then the Ohm char is concatenated to that String.
You can also begin with the empty String to get the desired output:
System.out.println("" + R + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");

Java: Issue when replacing Strings on loop

I'm building a small app which auto translates boolean queries in Java.
This is the code to find if the query string contains a certain word and if so, it replaces it with the translated value.
int howmanytimes = originalValues.size();
for (int y = 0; y < howmanytimes; y++) {
String originalWord = originalValues.get(y);
System.out.println("original Word = " + originalWord);
if (toReplace.contains(" " + originalWord.toLowerCase() + " ")
|| toCheck.contains('"' + originalWord.toLowerCase() + '"')) {
toReplace = toReplace.replace(originalWord, translatedValues.get(y).toLowerCase());
System.out.println("replaced " + originalWord + " with " + translatedValues.get(y).toLowerCase());
}
System.out.println("to Replace inside loop " + toReplace);
}
The problem is when a query has, for example, '(mykeyword OR "blue mykeyword")' and the translated values are different, for example, mykeyword translates to elpalavra and "blue mykeyword" translates to "elpalavra azul". What happens in this case is that the result string will be '(elpalavra OR "blue elpalavra")' when it should be '(elpalavra OR "elpalavra azul")' . I understand that in the first loop it replaces all keywords and in the second it no longer contains the original value it should for translation.
How can I fix this?
Thank you
you can sort originalValues by size desc. And after that loop through them.
This way you first replace "blue mykeyword" and only after you replace "mykeyword"
The "toCheck" variable is not explained what is for, and in any case the way it is used looks weird (to me at least).
Keeping that aside, one way to answer your request could be this (based only on the requirements you specified):
sort your originalValues, so that the ones with more words are first. The ones that have same number of words, should be ordered from more length to less.

If statement running when false

I'm attempting to write some code for a game in Java, however one of the if statements isn't working as expected.
if(player.gety() < y+row*tileSize){
player.draw(g);
System.out.println("Row: " + y+row*tileSize);
System.out.println("Player: " + player.gety());
}
When this code is run the output that I receive is:
Player: 200
Row: -79.99999999968651320
Player: 200
Row: -79.99999999968651320
Player: 200
Row: -79.99999999968651320
This doesn't make much sense as player.gety() is clearly larger than y+row*tileSize. Is there any reason why this would be happening?
String concatenation is what's tripping you up here. Specifically,
"Row: " + y+row*tileSize
is not the same thing as
"Row: " + (y+row*tileSize)
In the first case, you're getting
("Row: " + y)+ (row*tileSize)
where y is being converted to its String representation and concatenated onto "Row: ", and then the product of row * tileSize is getting converted to its String representation and concatenated onto that.
In the second case, you'd be getting (y + row * tileSize), a single numeric value, which would then be turned into a String representation and concatenated onto the String "Row: :"
This is actually behaving as demanded by the spec. When either operand of the + operator is a String, it no longer means "addition", it means "concatenation", and concatenation does not obey the arithmetical rules of precedence. Instead, it greedily coerces its other operand to a String value and cats the two together.
This can have some unexpected results, as you've discovered. Try adding the parens as suggested above, or printing out the values of the variables individually:
System.out.println("y = "+ y + " row = "+row + " tileSize = " + tileSize)
and it'll be easier to see what's happening.
EDIT:
I expect that you'll find that More likely, y = -79.999999999 (ie, -79.9, repeating) and row*tileSize=68651320. Adding those up you get substantially more than 200.
Yes, I don't think the Row output statement is showing what you think it's showing. Also, might player.draw(g) modify the result of player.gety()? Put the output statements first in the if-true block. Output each variable instead of an expression.

Java String formatting a line with different variable types

I need to put for example 5 spaces after the first variable
2 spaces_go_here 300 batch ordered (due on day 7)
this is the format of the line and it consists of an Integer + Integer + String
I've tried the following but without success.
System.out.printf("%-5d%d%s",i + " " + testProduct.getQuantity() + " batch");
Although printf("%-5s%s",.. works if I'm trying to put spaces in between two Strings
The arguments to the Variadic function PrintStream.printf(String, Object...) are comma separated, this
System.out.printf("%-5d%d%s",i + " " + testProduct.getQuantity() + " batch");
should be something like
System.out.printf("%-5d%d%s",i, testProduct.getQuantity()," batch");
Or
System.out.printf("%-5d%d batch",i, testProduct.getQuantity());

Categories