public?class?HelloWorld?{
????//完成?main?方法
????public?static?void?main(String[]?args)?{
????????
????????//?創建對象,對象名為hello
HelloWorld?hello?=?new?HelloWorld();?
????????
????????//?調用方法并將返回值保存在變量中
????????int?maxScore?=?hello.getMaxAge();
????????
//?輸出最大年齡
System.out.println("最大年齡為:"?+?maxScore);?
}
/*
?*?功能:輸出學生年齡的最大值?
?????*?定義一個無參的方法,返回值為年齡的最大值
?????*?參考步驟:
?????*?1、定義一個整形數組?ages?,保存學生年齡,數組元素依次為?18?,23?,21?,19?,25?,29?,17
?????*?2、定義一個整形變量?max?,保存學生最大年齡,初始時假定數組中的第一個元素為最大值
?????*?3、使用?for?循環遍歷數組中的元素,并與假定的最大值比較,如果比假定的最大值要大,則替換當前的最大值
?????*?4、使用?return?返回最大值
?*/
//public?int?getMaxAge()?{
????public?int?getMaxAge(){??????//這里為啥會報錯呢?該怎么修改呢?
int?ages[]={18,23,21,19,25,29,17};
int?max=ages[0];
for(int?i=0;i<ages.length;i++){
if(max<ages[i]){
max=ages[i];
}
return?max;
}???
}
}
2 回答
已采納

ziom
TA貢獻948條經驗 獲得超1109個贊
public?int?getMaxAge(){??????//這里為啥會報錯呢?該怎么修改呢????????? ????int?ages[]={18,23,21,19,25,29,17}; ????int?max=ages[0]; ????for(int?i=0;i<ages.length;i++){ ????????if(max<ages[i]){ ????????????max=ages[i]; ????????} ????????//?return?max; ????}??? ????//?要確保方法最終會返回一個整型值,如果return?max;寫在for循環中,則無法保證方法最終會有返回值 ????return?max; }
添加回答
舉報
0/150
提交
取消