This question already has answers here:
Add bytes with type casting, Java
                                
                                    (7个答案)
                                
                        
                        
                            Why is the sum of bytes integer? [duplicate]
                                
                                    (1个答案)
                                
                        
                        
                            Java: why do I receive the error message “Type mismatch: cannot convert int to byte”
                                
                                    (4个答案)
                                
                        
                                2年前关闭。
            
                    
我想知道为什么//1语句被编译器接受,而//2语句不被接受

    //1
    int k = 99999999;
    byte l = (byte)k;

    //2
    byte b = 1;
    int i = 10;
    byte z = (byte)i+b; //compiler rejected


Type mismatch: cannot convert from int to byte using ternary operator给了我一些想法,但是我不明白为什么编译器可以将l中的变量//1解析为可接受的,而不是将i解析为//2

最佳答案

您只将第一个数字byte而不是全部和转换为i。您必须添加方括号:

byte z = (byte) (i+b);

10-05 22:23
查看更多