慕萊塢1282154
2017-07-19 20:57:34
package com.jichutest;public class test5 {?? ?public int show(){?? ??? ?int[] ages={18,23,21,19,25,29,17};?? ??? ?int max=ages[0];?? ??? ?for(int i = 0;i<=ages.length;i++ ){?? ??? ??? ?if(ages[i]>max){?? ??? ??? ??? ?max=ages[i];?? ??? ??? ?}?? ??? ??? ??? ??? ??? ??? ?}?? ??? ?return max;?? ??? ??? ??} ??? ??? ?public static void main(String[] args){?? ??? ?test5 hello = new test5();?? ??? ?int max=hello.show();?? ??? ?System.out.println("年齡最大為:"+max);?? ???? }}
3 回答

望遠
TA貢獻1017條經驗 獲得超1032個贊
for(int?i?=?0;i<=ages.length;i++?)
改成
for(int?i?=?0;i<ages.length;i++?)
否則會數組下標越界


丶看著遠方不悲傷不仰望
TA貢獻9條經驗 獲得超10個贊
在處理數組,集合,這些問題的時候要注意,size(),length()得到的是長度的大小,是從1開始,但是你進行循環拿值的時候,是從0開始的。
添加回答
舉報
0/150
提交
取消