早教吧 育儿知识 作业答案 考试题库 百科 知识分享

为什么定义bytea,且没有超出byte的取值范围,但java还是报错呢?bytescore[]=newbyte[5];score[0]=1;score[1]=2;score[2]=3;score[3]=4;score[4]=5;bytea;a=score[0]+score[1]+score[2]+score[3]+score[4];System.out.println("

题目详情
为什么定义byte a,且没有超出byte的取值范围,但java还是报错呢?
byte score[]=new byte[5];
score[0]=1;
score[1]=2;
score[2]=3;
score[3]=4;
score[4]=5;
byte a;
a=score[0]+score[1]+score[2]+score[3]+score[4];
System.out.println(" 成绩之和为 ="+a);
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to byte
at array.main(array.java:16)
▼优质解答
答案和解析
进行narrowing conversion(缩小转换)时存在数据丢失的风险,所以编译器会强制你造型.简单说就是你要进行强转,a=(byte)();