简体   繁体   English

当我尝试调用在主方法中创建的方法时,出现错误

[英]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. 由于错误状态,您传递的是2个int数,而不是一个short和一个字节。 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: 错误的原因是,在Java中,整数文字是int除非:

  1. you specify it as a long eg 128L (There is no specifier for short or byte unfortunately) 您将其指定为long 128L例如128L (不幸的是,没有short 128Lbyte说明符)
  2. assign it to another integer type eg short s = 1; 将其分配给另一个整数类型,例如short s = 1;
  3. you cast it explicitly eg (short) 4 您明确地将其投射,例如(short) 4
  4. you have a Widening primitive conversion eg pass an int to a method expecting a long 你有一个扩展原语转换,例如将一个int传递给一个期望long int的方法

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 . intshortbyte 转换称为Narrowing基本转换 ,如果int太大而不能放入short ,则通常可能会失败。

Documentation 文档

Try creating variables before calling the subtractNumbers method. 在调用subtractNumbers方法之前,尝试创建变量。 That way, you can set the type you want and it won't complain about the types not being the same. 这样,您可以设置所需的类型,而不会抱怨类型不相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM