Java printing a String containing an integer - java

I have a doubt which follows.
public static void main(String[] args) throws IOException{
int number=1;
System.out.println("M"+number+1);
}
Output: M11
But I want to get it printed M2 instead of M11. I couldn't number++ as the variable is involved with a for loop, which gives me different result if I do so and couldn't print it using another print statement, as the output format changes.
Requesting you to help me how to print it properly.

Try this:
System.out.printf("M%d%n", number+1);
Where %n is a newline

Add a bracket around your sum, to enforce the sum to happen first. That way, your bracket having the highest precedence will be evaluated first, and then the concatenation will take place.
System.out.println("M"+(number+1));

It has to do with the precedence order in which java concatenates the String,
Basically Java is saying
"M"+number = "M1"
"M1"+1 = "M11"
You can overload the precedence just like you do with maths
"M"+(number+1)
This now reads
"M"+(number+1) = "M"+(1+1) = "M"+2 = "M2"

Try
System.out.println("M"+(number+1));

Try this:
System.out.println("M"+(number+1));

A cleaner way to separate data from invariants:
int number=1;
System.out.printf("M%d%n",number+1);

System.out.println("M"+number+1);
Here You are using + as a concatanation Operator as Its in the println() method.
To use + to do sum, You need to Give it high Precedence which You can do with covering it with brackets as Shown Below:
System.out.println("M"+(number+1));

System.out.println("M"+number+1);
String concatination in java works this way:
if the first operand is of type String and you use + operator, it concatinates the next operand and the result would be a String.
try
System.out.println("M"+(number+1));
In this case as the () paranthesis have the highest precedence the things inside the brackets would be evaluated first. then the resulting int value would be concatenated with the String literal resultingin a string "M2"

If you perform + operation after a string, it takes it as concatenation:
"d" + 1 + 1 // = d11
Whereas if you do the vice versa + is taken as addition:
1 + 1 + "d" // = 2d

Related

Java StringBuilder character appending returns unwanted number

I am very sorry if this is a basic question which has been answered before (I tried looking but I did not find anything)
I am trying to write the following Java method:
String winningCard(String trick, char trump) {
StringBuilder sb = new StringBuilder();
char suit;
char rank;
for(int i = 1; i < trick.length(); i+=2) {
if(trick.charAt(i) == trump) {
suit = trick.charAt(i);
rank = trick.charAt(i-1);
sb.append(rank + suit); //issue here, returns a weird number
break;
}
}
String result = sb.toString();
return result;
}
When called with these arguments "8s7hQd", 'h' for example, it is supposed to return "7h".
If I change the StringBuilder to only append either the suit or the rank, it does it just fine, but if I put it the way it is above it returns "159" which I believe has something to do with the unicode encoding.
I'd very much appreciate if a kind sould could tell me what I am missing.
Thanks in advance
suit and rank are basically numbers. The + is adding these numbers and appending it.
If you place a "" between, the chars will be appended as you intend, because it forces the compiler to use the + with a String.
sb.append(rank + "" + suit);
append(rank).append(suit);
Should do the trick
+ is a tricksy thing, because it means different things in different contexts.
If at least one of the operands is a String, it acts as the string concatenation operator.
If both of the operands are numbers, or convertible to numbers via unboxing, then it acts as the numeric addition operator.
You are giving it two chars: these are numbers, so numeric addition occurs.
Before adding the two chars, they are widened to int; the result is an int too. And it is this int that you are appending to the string builder, hence the "unwanted" number.
So, either avoid using the addition operator at all (best):
sb.append(rank).append(suit);
Or make sure you are using the string concatenation operator:
sb.append("" + rank + suit);
// Left-associative, so evaluated as
// ("" + rank) + suit
sb.append(String.valueOf(rank) + suit);
// Etc.
But actually, you don't need to do either: just append the substring:
sb.append(trick, i-1, i+1);
This extracts a portion of the trick string, as trick.substring(i-1, i+1) would, but does it without creating a new string.
And you don't need a loop
You can say directly that those chars should be interpreted as String by
sb.append(String.valueOf(rank) + String.valueOf(suit))

Is left to right a higher precedence then the object String?

Is left to right a higher precedence then the object String?
For my print statement as below I got this. Please explain.
class triangle{
public static void main(String[]args){
System.out.println(1+2+"hello");
System.out.println("hello"+1+2);
}
}
Also why do I need to put a cast to a floating x=1.2F;
and not double x=1.2;?
The + operator is left associative. Whether concatenation happens or summation happens is a result of the left-associativity.
When you are doing String + something what are you doing it is concatenating both elements, not sum the numbers.
You can concatenate two Strings like this:
string1 + string2
but also you can do
"" + string1
It only takes part if you are using a plus element after an String. If you sum before the String, the result of your sum will be shown and then the String will be concatenate to that sum.
You can also check on Oracle docs for more info (in the first section).

evaluating variable int/string

int x = 20;
double d = 3.1416;
String s ="H";
those are my variables and I have to give the type the next lines evaluate to.
d/x + "";
is evaluating to double variable type (0.15708), is that correct?
You'd be right if we didn't have that pesky "" at the end!
Add "" to the end of something like this makes it into a String. It can actually be a handy shortcut - instead of having to use something like String.valueOf(), you could just do 4/2 + "", which makes it into a string.
To reiterate,
d/x would be a double, since you are adding a floating point.
But a double + "" = String.
I hope that helps. Good luck :)
You are wrong.
d/x + ""; is a String. This happens because when you are using the + operator, if any of the 2 sides is a String, then string concatenation happens and of course the result is a String.
By the way you can check that indeed it is a String by using the getClass() method. Note that if you remove the "" and use the getClass() you will get an error. This happens because d/x is a double, i.e a primitive type, so it can't use the method getClass(). In your example:
System.out.println((d/x + "").getClass()); will return java.lang.String

Parsing Java String type Error

What i'm trying to do is incorporate interface methods to complete a task given the variables inside of a string. The string i'm given, "s" can be made up numbers, +, -, and * symbols. The integer return is fairly easy as all i'm doing is returning an integer interface method of that int. However, for the other 3 symbols, I need to recursively incorporate a method to find the left and right nodes. I've posted my code below...
public static Expression parseString( String s ) {
String[] parse = s.split("\\s+");
String[] parsecopy;
Expression exp1;
Expression exp2;
if(s == null) {
return null;
}
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
else if() {
The problem - So my code creates a copy of the original string to find the next item in that string. I do this by using the Array function, copyOfRange(). However, when I want to call exp2 = parseString(parsecopy), i'm receiving an error because parseString takes in a string argument which has to be of the type String[]. The reason i'm trying to get parsecopy instead of parsecopy[0] is because parsecopy wouldn't create an endless loop and I would actually be able to iterate through the string.
Error code - The method parseString(String) in the type Parse is not applicable for the arguments (String[])
if(parse[0].equals("+")) {
exp1 = parseString(parse[0]);
parsecopy = Arrays.copyOfRange(parse, 2, parse.length);
exp2 = parseString(parsecopy);
return new AddExpression(exp1, exp2);
}
exp1 = parseString(parse[0]);
you are doing recursive calling here.
Since the parameter you pass to split is a regex, you can simply do:
String[] ss = "12121+34234 *23423 -123123 *123123-12312+1231231-123123".split("\\s?[\\+\\-\\*]\\s?");
this way you split your string wherever you got a +, - , or * (possibly with a whitespace after or before).
And please do the null-check of the string before split it :D
Hope it helps.
It seems like you want to check parse[1] equals "+" rather than parse[0].
You would expect 1 + 2 rather than + 1 2.

Weird Java String comparison

I'm having a minor issue with Java String comparisons.
I've written a class which takes in a String and parses it into a custom tree type. I've written a toString class which then converts this tree back to a String again. As part of my unit tests I'm just checking that the String generated by the toString method is the same as the String that was parsed in the first place.
Here is my simple test with a few printouts so that we can see whats going on.
final String exp1 = "(a|b)";
final String exp2 = "((a|b)|c)";
final Node tree1 = Reader.parseExpression2(exp1);
final Node tree2 = Reader.parseExpression2(exp2);
final String t1 = tree1.toString();
final String t2 = tree2.toString();
System.out.println(":" + exp1 + ":" + t1 + ":");
System.out.println(":" + exp2 + ":" + t2 + ":");
System.out.println(exp1.compareToIgnoreCase(t1));
System.out.println(exp2.compareToIgnoreCase(t2));
System.out.println(exp1.equals(t1));
System.out.println(exp2.equals(t2));
Has the following output; (NB ":" - are used as delineators so I can ensure theres no extra whitespace)
:(a|b):(a|b):
:((a|b)|c):((a|b)|c):
-1
-1
false
false
Based on manually comparing the strings exp1 and exp2 to t1 and t2 respectively, they are exactly the same. But for some reason Java is insisting they are different.
This isn't the obvious mistake of using == instead of .equals() but I'm stumped as to why two seemingly identical strings are different. Any help would be much appreciated :)
Does one of your strings have a null character within it? These might not be visible when you use System.out.println(...).
For example, consider this class:
public class StringComparison {
public static void main(String[] args) {
String s = "a|b";
String t = "a|b\0";
System.out.println(":" + s + ":" + t + ":");
System.out.println(s.equals(t));
}
}
When I ran this on Linux it gave me the following output:
:a|b:a|b:
false
(I also ran it on Windows, but the null character showed up as a space.)
Well, it certainly looks okay. What I would do would be to iterate over both strings using charAt to compare every single character with the equivalent in the other string. This will, at a minimum, hopefully tell you the offending character.
Also output everything else you can find out about both strings, such as the length.
It could be that one of the characters, while looking the same, may be some other Unicode doppelganger :-)
You may also want to capture that output and do a detailed binary dump on it, such as loading it up into gvim and using the hex conversion tool, or executing od -xcb (if available) on the captured output. There may be an obvious difference when you get down to the binary examination level.
I have some suggestions
Copy each output and paste in Notepad (or any similar editor), then
copy them again and do something like this
System.out.println("(a|b)".compareToIgnoreCase("(a|b)"));
Print out the integer representation of each character. If it is a weird unicode, the int representation will be different.
Also what version of JDK are you using?

Categories