首页 > 解决方案 > 错误 - :不兼容的类型:从 int 到 short 的可能有损转换

问题描述

我知道当我们尝试向下转换值时会发生此错误,但在我的代码中我无法弄清楚我在哪里向下转换了值。

class TestClass {
    public static void main(String args[] ) throws Exception {
        TestDemo obj=new TestDemo();
        TestDemo2 obj1= new TestDemo2();
        obj.show(5);
        obj1.show("helloworld");
    }
}
class TestDemo{
    public void show(short N){
        System.out.println(N*2);
    }  
}
class TestDemo2{
    public Void show(String S){
        System.out.println(S);
    }
}

标签: javaexception

解决方案


由于 obj.show(5) 而发生此错误。

两个修复`你可以做任何事情:

    class TestClass {
    public static void main(String args[] ) throws Exception {
        TestDemo obj=new TestDemo();
        TestDemo2 obj1= new TestDemo2();
        obj.show((short)5);
        obj1.show("helloworld");
    }
}
class TestDemo{
    public void show(short i){
        
        System.out.println(i*2);
    }  
}
class TestDemo2{
    public void show(String S){
        System.out.println(S);
    }
}

第二版

    class TestClass {
    public static void main(String args[] ) throws Exception {
        TestDemo obj=new TestDemo();
        TestDemo2 obj1= new TestDemo2();
        obj.show(5);
        obj1.show("helloworld");
    }
}
class TestDemo{
    public void show(int i){
        
        System.out.println(i*2);
    }  
}
class TestDemo2{
    public void show(String S){
        System.out.println(S);
    }
}

推荐阅读