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));
    }    
}当我编译和运行程序时,我得到了错误,如下所示:
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为什么代码会导致错误?我想知道。
提前感谢您的帮助,我们将不胜感激。
发布于 2016-02-18 22:07:49
正如错误所述,您传递的是两个整型数字,而不是一个短整型数字和一个字节。尝试:
System.out.println(subtractNumbers((short) 127, (byte) 127, 0.0f));或者将您的方法更改为:
public static short subtractNumbers(int a, int b, float k) {
    return (short) (a + b - (int) k);
}发布于 2016-02-18 22:16:41
错误的原因是,在Java语言中,整型文字是一个int,除非:
将其指定为long,例如128L (没有将其转换为另一个整数类型的short或byte说明符,例如short s = 1;
(short) 4
int传递给需要long的方法
从int到short或byte的转换称为缩小原语转换,如果int太大而无法放入short,则通常可能会失败。
发布于 2016-02-18 22:08:47
在调用subtractNumbers方法之前尝试创建变量。这样,你可以设置你想要的类型,并且它不会抱怨类型不同。
https://stackoverflow.com/questions/35483589
复制相似问题