简体   繁体   中英

Returning String from a int function

My question is simple, im having trouble on returning my value(sorry im a beginner)

int modulo10(String a, String b) {
String res;
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
x = (x+y)%y;

res = Integer.toString(x);
return res;
}

Java is a strongly typed language. From the line String res; , res is a String variable, but you are trying to put an Integer inside.

As x is an Integer and contains the value you want to return, you can just return x instead.

You can convert an Integer into an int , because of autoboxing , and you can do the reverse because of unboxing. More generally, you can convert any primitive type into its wrapper class ( Integer for int , Boolean for boolean , etc).

You cannot do that. You declared that your method returns an int and you try to return a String - pick one. Either change your method to return String or just return x; .

You can't return a string from a function having int return type .

int modulo10 (int a, int b){
int x;

x = (a+b)%b;

return x;

}

change the return type of the method

int modulo10(String a, String b) {

into

String modulo10(String a, String b) {

or simply return your int x without converting it into String res, depends what you want to do with it

If String a,b conatains any non-numeric value it will give ParseException. And As your method return int value,you are returning string value.So Java will throw exception.Hope you will get your point.

将数据类型从 int 更改为 String

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