要求通過定義無參帶返回值的方法來實現,返回值爲最大年齡 2

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[] stuAge = {18,23,21,19,25,29,17};
    int max = 0;
for(int i:stuAge)
    {
      max=max>i?max:i;
    }
    return max;
}

}

for (int age : ages){
if (age > max)
max = age;
}




public int getMaxAge() {
        //裝了個波一啊
   int[] ages = {18,23,21,19,25,29,17};
        Arrays.sort(ages);
        int max = ages[ages.length-1];
        return max;    
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章