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()? ? { ? ? int []ages={18,23,21,19,25,29,17};? ? int max=ages[0];? ? for(int i=1;i<ages.length;i++)? ? {? ? ? ? if(max<ages[i])? ? ? ? max=ages[i];? ? }? ? return max; }}
添加回答
舉報
0/150
提交
取消