Adding strings?
Hello,
I am making a program, in which I need to create strings with a variable in the middle. Here is the code I have so far:
myString ="c" + Integer.toString(a)+".gif"
I want it to output c42.gif while a = 42
How can I add strings together like this in java? Thanks!
[350 byte] By [
cmpolisa] at [2007-11-27 10:41:11]

Have you tried to compile and run what you have?
doesnt this work already?
I wrapped up a quick demo:
import java.io.*;
public class MyString {
public static void main(String[] args) {
//first version
System.out.println("First version:");
int a = 42;
String myString2 = "c" + Integer.toString(a)+".gif";
System.out.println("Get: " + myString2 + "\n");
//second version
System.out.println("Second version:");
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number of gif: ");
StringaskNumber = br.readLine();
String myString = "c" + askNumber + ".gif";
System.out.println("get: " + myString);
}
catch(IOException IOE){}
}
}
> Hello,
> I am making a program, in which I need to create
> strings with a variable in the middle. Here is the
> code I have so far:
> code]myString = "c" +
> Integer.toString(a)+".gif"[/code]
> I want it to output c42.gif while a = 42
>
> How can I add strings together like this in java?
> Thanks!
that should work fine if you compile it...
just compile and run ....
vsavia at 2007-7-28 19:11:12 >

> Hello,
> I am making a program, in which I need to create
> strings with a variable in the middle. Here is the
> code I have so far:
> code]myString = "c" +
> Integer.toString(a)+".gif"[/code]
> I want it to output c42.gif while a = 42
>
> How can I add strings together like this in java?
> Thanks!
You better use StringBuffer
StringBuffer sb = new StringBuffer();
sb.append("c");
sb.append(Integer.toString(a));
sb.append(".gif");
return sb.toString();
> You better use StringBuffer
> StringBuffer sb = new StringBuffer();
> sb.append("c");
> sb.append(Integer.toString(a));
> sb.append(".gif");
> return sb.toString();
Why? He's not adding thousands of strings together in some loop, a situation where I agree that stringbuffer would be advantagous. No, when just adding a few strings here and there as the OP is doing, there is essentially no advantage to using StringBuffer.
The call to Integer.toString is unecessary.
myString = "c" + a + ".gif";
> Why? He's not adding thousands of strings together
> in some loop, a situation where I agree that
> stringbuffer would be advantagous. No, when just
> adding a few strings here and there as the OP is
> doing, there is essentially no advantage to using
> StringBuffer.
I think you missed the joke :)
It would have been more obvious if the response suggested using:int a = 42;
StringBuffer sb = new StringBuffer();
sb.append("c" + Integer.toString(a) + ".gif");
return sb.toString();