Reputation: 9
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
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
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
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
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