我在 Windows 上的 Eclipse 上编写了我的第一个 Java 程序。我最近开始在 Linux 上进行 Java 编程。
当我尝试在 Linux 上编译上述程序时,它工作正常,但当我尝试在 Windows 上编译时,出现以下错误。
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Type mismatch: cannot convert from int to short
Type mismatch: cannot convert from double to float
public class TypeDemo {
public static void main (String args[])
{
byte b = 8;
long a = 1000011334;
int c = 76;
short s = 99789;
float f = 99.99;
double d = 99979.9879;
boolean bool = true;
char ch = 'y';
System.out.println ("b = "+b);
System.out.println ("a = "+a);
System.out.println ("c = "+c);
System.out.println ("s = "+s);
System.out.println ("f = "+f);
System.out.println ("d = "+d);
System.out.println ("bool = "+bool);
System.out.println ("ch = "+ch);
}
}
最佳答案
When I try to compile the above program on Linux it does work fine
这实际上很令人惊讶,我买不起。再检查一遍,应该不会。
short
是一个 16 位有符号 2 的补码整数。它的最大值是 32767
,您要为其分配 99789
。肯定是超出范围了。您需要显式地将其类型转换为 short
:
short s = (short)99789;
short s1 = 100; // this would however work
虽然你会在那里看到奇怪的输出。多余的位将被截断。最好直接使用int
。
现在,对于float
,浮点文字默认为double
。要获得 float
,您需要在末尾附加 F
或 f
。因此,将其更改为:
float f = 99.99f;
关于java:简单类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205354/