简体   繁体   中英

While I am trying to call my method, which is created in the main method, I am getting errors

public class MyClass
{
    public  static short subtractNumbers (short a, byte b, float k )
    {
        int x=(short)a;
        int y=(short)b;
        int z=(short)k;
        return (short)(x+y-z);
    }
    public static void main (String[] args)
    {
        System.out.println(subtractNumbers(127,127,0.0f));
    }    
}

When I compile and run the program, I am getting errors, as:

error: method subtractNumbers in class MyClass cannot be applied to given types;

System.out.println(subtractNumbers(127,127,0.0f));

required: short,byte,float

found: int,int,float

reason: actual argument int cannot be converted to short by method invocation conversion

Why are the code causing the errors? I am wondering.

Thanks in advance for the help it would be appreciated.

As the error states you are passing 2 int numbers instead of a short and a byte. Try:

System.out.println(subtractNumbers((short) 127, (byte) 127, 0.0f));

Or change your method to:

public static short subtractNumbers(int a, int b, float k) {
    return (short) (a + b - (int) k);
}

The reason for the error is that in Java an integer literal is an int unless:

  1. you specify it as a long eg 128L (There is no specifier for short or byte unfortunately)
  2. assign it to another integer type eg short s = 1;
  3. you cast it explicitly eg (short) 4
  4. you have a Widening primitive conversion eg pass an int to a method expecting a long

A conversion from int to short or byte is called a Narrowing primitive conversion and it may fail generally, if the int is too large to fit in a short .

Documentation

Try creating variables before calling the subtractNumbers method. That way, you can set the type you want and it won't complain about the types not being the 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