Reputation:
Hello I want to string concatenate two numbers as in the code below:
tmp2 = Integer.toString(preresult) + tmp2.substring(2, tmp2.length());
Tmp2 is a string declared from before. Preresult is a integer that contains a number. If I print this line it adds the two values instead of string concatenation.
If I change Integer.toString(preresult) to for example Integer.toString(5) it string concatenates as I would like it to do. But having Integer.toString(preresult) it adds the two numbers instead of string concatenating.
The code for preresult :
preresult = Integer.parseInt(tmp2.substring(0, 1)) + Integer.parseInt(tmp2.substring(1, 2));
//It picks numbers from tmp2 and adds them together. If I print preresult it gives me a int (for example 9)
Once again please help me concatenate these two strings instead of adding them:
tmp2 = Integer.toString(preresult) + tmp2.substring(2, tmp2.length());
New to java please mercy :)
Upvotes: 0
Views: 245
Reputation: 2982
The line you are giving us does concatenate the String
s, but maybe you got confused because the line before sums them:
// tmp2 == "45" (taken from your comment)
preresult = Integer.parseInt(tmp2.substring(0, 1)) + Integer.parseInt(tmp2.substring(1, 2));
// |------ "4" -------| |-------- "5" -----|
// |--------------- 4 -----------------| |------------------ 5 --------------|
// preresult == 4 + 5 == 9
println(tmp2); // prints the "45" (unchanged)
tmp2 = Integer.toString(preresult) + tmp2.substring(2, tmp2.length());
// |-- 9 --| |"45"|
// |----------- "9" ---------| |------------- "" -------------|
// tmp2 == "9" + "" == "9"
println(tmp2); // prints "9"
So your first line sums the two digits 4 and 5, which results in 9. The line you had given us just concatenates that result "9"
(as String
) with another empty String
and therefore keeps the "9"
.
Upvotes: 0
Reputation: 327
Are you looking for this type of operation
class String1
{
public static void main(String args[])
{
int a = 100;
int b = 200;
String s1 = Integer.toString(a);
String s2 = Integer.toString(b);
System.out.println(s1+s2);
}
}
Output - 100200
Upvotes: 1