简体   繁体   中英

How to keep different types of the function and the arguments

The following code:

public static void main(String[] args) {
int retval=something(3,5);
System.out.println(retval);
    }

public static float something(int first, int second){
return first+second;
}

...crashes with compile-error:

error: possible loss of precision
int retval=something(3,5);
                        ^
  required: int
  found:    float
1 error

Why does float type of the function influence the types of the arguments?

UPD. Not asking how to improve the design, I'm asking why I cannot pass agruments of the type different that return of the function.

The return type doesn't influence the type of the arguments. The reason for your error is trying to assign the float return type to an int variable, which is not possible without an explicit cast.

That being said, it makes little sense for a method that accepts two ints and returns their sum to return float.

Either change your return type to int :

public static int something(int first, int second){
    return first+second;
}

Or change the argument types to float :

public static float something(float first, float second) {
    return first+second;
}

That's because you return float value and try to assign it to int. Try following:

public static void main(String[] args) {
float retval=something(3,5);
System.out.println(retval);
    }

public static float something(int first, int second){
return first+second;
}

Alternatively chage the return type of somthing() to int :

 public static int something(int first, int second){
    return first+second;
    }

However If you don't want to change type, you can cast the return type to int:

public static void main(String[] args) {
        int retval=(int)something(3,5);
        System.out.println(retval);
            }

        public static float something(int first, int second){
        return first+second;
        }

make sure that you argument types and return types are of same type if method is of some calculation.

you should have:

1.

public static int add(int first, int second){
    return first+second;
}

2.

public static float add(float first, float second) {
    return first+second;
}

because different data type does not make sense.

and keep in mind that whatever the return type of method, the variable which is going to hold result of method is same.

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