GinoT
GinoT

Reputation: 1

Trying to convert int type to string type

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

Answers (5)

lenwe
lenwe

Reputation: 100

Try using the format() method:

public String toString(int x, int y){
    return String.format("(%d,%d)",x,y);
}

Upvotes: 0

itzmebibin
itzmebibin

Reputation: 9439

There are multiple ways:

  1. String.valueOf(x)
  2. "" + x
  3. 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

Benjamin Lowry
Benjamin Lowry

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

Asahi Sara
Asahi Sara

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

David Dennis
David Dennis

Reputation: 722

You can convert a int to a string using:

Integer.toString(number)

or

String.valueOf(number)

Upvotes: 1

Related Questions