[英]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
除非:
long
eg 128L
(There is no specifier for short
or byte
unfortunately) long
128L
例如128L
(不幸的是,没有short
128L
或byte
说明符) short s = 1;
short s = 1;
(short) 4
(short) 4
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
. 从
int
到short
或byte
转换称为Narrowing基本转换 ,如果int
太大而不能放入short
,则通常可能会失败。
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.