gpt4 book ai didi

java - 错误 : incompatible types: possible lossy conversion from int to short. 我不知道为什么会收到此错误消息

转载 作者:搜寻专家 更新时间:2023-10-31 19:59:26 28 4
gpt4 key购买 nike

public class Demo 
{
public static void main(String[] args)
{
int a=10,b=20;
short c = (a<b)?a:b;
System.out.println(c);
}
}

这是我的程序,我遇到以下错误,为什么我没有得到

"Demo.java:6: error: incompatible types: possible lossy conversion from int to short
short c = (a<b)?a:b;
1 error"

我写了带有变量声明的“final”,它工作正常。但为什么会这样呢?

public class Demo 
{
public static void main(String[] args)
{
final int a=10,b=20;
short c = (a<b)?a:b;
System.out.println(c);
}
}

最佳答案

要回答您的问题,您基本上是向下转换 int 数据类型为short Java 中 Not Acceptable 情况。为了详细描述,下面是详细描述:-

案例 1:-

public class Demo 
{
public static void main(String[] args)
{
int a=10,b=20;
short c = (a<b)?a:b;
System.out.println(c);
}
}

在这种情况下,您只是将数据类型从int向下转换short,这是抛出

error: incompatible types: possible lossy conversion from int to short

案例 2:-

public class Demo 
{
public static void main(String[] args)
{
final int a=10,b=20;
short c = (a<b)?a:b;
System.out.println(c);
}
}

In this scenario, since you have declared your variables viz. a & b as final. As a result, both the values becomes CONSTANT for variable c. It means for the variable c, the values of a & b won't get changed & it has been finalized to 20 which is in range of short data type (-32,768 to 32,767). Therefore, you won't get any error unless & until you keep the value within the range.

真实测试用例:-

public class Demo 
{
public static void main(String[] args)
{
final int a=32768,b=32788;
short c = (a<b)?a:b;
System.out.println(c);
}
}

编译这个类,看看它的神奇之处!您将再次遇到相同的错误。

For your further understanding, please refer here to get a clear picture in general.

这个故事的寓意:- 只是不要贬低你的数据类型!!

关于java - 错误 : incompatible types: possible lossy conversion from int to short. 我不知道为什么会收到此错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53774145/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com