Reputation: 1
First time posting. If I have two variables named x and y and they both are holding an int value; is it possible to convert the value they are holding into a string type? I am doing some school work and it's part of a class file names MyPoint. Here is the exact instruction:
"A method named toString that returns the values of the x and y in the following String format:(x,y)"
Can any body point me in the right direction? I keep getting errors saying that it is incompatible types.
Upvotes: 0
Views: 59
Reputation: 100
Try using the format() method:
public String toString(int x, int y){
return String.format("(%d,%d)",x,y);
}
Upvotes: 0
Reputation: 9439
There are multiple ways:
String.valueOf(x)
"" + x
Integer.toString(x)
Try like,
public String toString(int x, int y){
return (Integer.toString(x) + "," + Integer.toString(y));
}
or,
public String toString(int x, int y){
return (String.valueOf(x) + "," + String.valueOf(y));
}
Upvotes: 1
Reputation: 3799
From what I understand about your problem, the code should look something like this:
public String toString(int x, int y){
return "(" + Integer.toString(x) + "," + Integer.toString(y) + ")";
}
When 1 and 3 are passed into the method as parameters, "(1,3)" is returned.
This uses the Integer.toString(number) method.
EDIT:
As pointed out by @dave, you can also just use
public String toString(int x, int y){
return "(" + x + "," + y + ")";
}
Upvotes: 1
Reputation: 153
Try using:
Integer.toString(numberX + numberY); //Convert integer values to String
or
String.valueOf(intX + intY); //Convert some values type to String
or
String str = "" + X + "" + Y; //Convert integer values and adds to text message
Hope help you.
Upvotes: 0
Reputation: 722
You can convert a int to a string using:
Integer.toString(number)
or
String.valueOf(number)
Upvotes: 1