java:简单类型转换

标签 java windows eclipse

我在 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,您需要在末尾附加 Ff。因此,将其更改为:

float f = 99.99f;

关于java:简单类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205354/

相关文章:

c# - 以编程方式获取 Windows 操作系统版本

windows - Windows Phone 7 英语单词词典数据库

eclipse - Ctrl + Shift + R 在 Eclipse 中不起作用

java - IntelliJ 中的 InputStream 为空,但 Eclipse 中则不然

java - 如何运行 Spark Java 程序

java - 错误将此数据转换为日期 ("HH:mm a")、("dd MM")和 ("yyyy")。如何将其划分为 :D 部分

windows - 动态加载exe文件

java - TextView导致应用程序崩溃

java - 字符串到字符数组和字符串数组

每次启动程序时 Eclipse 索引器都会运行