我已经在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);
    }
}

最佳答案

当我尝试在Linux上编译以上程序时,它确实可以正常工作


实际上,这非常令人惊讶,我买不到。再次检查,不应该。

short是16位带符号2的补码整数。它的最大值是32767,并且您正在为其分配99789。绝对超出范围。您需要显式地将其转换为short

short s = (short)99789;
short s1 = 100;   // this would however work


尽管您会在那里看到奇怪的输出。多余的位将被截断。最好直接使用int

现在,在float的情况下,默认情况下浮点文字是double。要获取float,您需要在末尾附加Ff。因此,将其更改为:

float f = 99.99f;

09-04 13:51
查看更多