Kangaroo
Kangaroo

Reputation: 9

Convert int to string and return

I want the code to get an int as an argument and add 3 if the age is odd and adds 2 if even and then return as string.

With this code i get

incompatible types: int cannot be converted to String

Hasn't it been converted at line 9?

public String whatAge() {

    Scanner input = new Scanner(System.in);
    int age = input.nextInt();

    if (age % 2 == 0) {
        age += 2;
    }
    else 
        age += 3;

    Integer.toString(age);

    return age;
}

Upvotes: 0

Views: 6944

Answers (5)

Stephen C
Stephen C

Reputation: 718758

Your code says this:

    Integer.toString(age);  // line #9
    return age;

That should be:

    return Integer.toString(age);

Hasn't it been converted at line 9?

Well yes ... but then you threw away the String result of the toString call and returned the original int instead.

Upvotes: 3

Santosh Giri
Santosh Giri

Reputation: 119

You can try in this way return Integer.toString(age);

public class intToS {

    public String whatAge() {

        int age = 25;

        if (age % 2 == 0) {
            age += 2;
        } else
            age += 3;

        return Integer.toString(age);
    }
    public static void main(String[] args) {
        intToS obj = new intToS();
        System.out.println("Age = "+obj.whatAge());
    }
}

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

You need to assign returning String to variable or you can just return it. toString() return the String value of Integer you need to take it. Here you didn't take that returning String.

 String str=Integer.toString(age); // str is the returning String
 return str;

Or

return Integer.toString(age); // returning result of toString()

Upvotes: 1

Nafta
Nafta

Reputation: 71

do it like this and it should work:

return age.toString();

Upvotes: -2

apomene
apomene

Reputation: 14389

You arent saving the converted value to any string before returning it, you return age which remains an int:

String result=Integer.toString(age);

return result;

Upvotes: 0

Related Questions