简体   繁体   中英

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;
}

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.

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()

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());
    }
}

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;

这样做,它应该可以工作:

return age.toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM