天天看點

【JavaSE】Java方法練習題

1 ) 編寫類

AA

,有一個方法:判斷一個數是奇數

odd

還是偶數, 傳回

boolean

MethodExercise01.java

思路:

1. 方法的傳回值類型 boolean
2. 方法的名字 isOdd
3. 方法的形參 (int num)
4. 方法體,判斷           
public class MethodExercise01 {
    public static void main(String[] args) {
        AA a = new AA();
        if (a.isOdd(1)){
            System.out.println("是奇數");
        }else{
            System.out.println("是偶數");
        }
    }
}
class AA{

    public boolean isOdd(int num){
        if(num % 2 != 0){
            return true;
        }else{
            return false;
        }
    }
}           
  • 或直接把

    if-else

    判斷替換為三元運算都是可以的
return num % 2 != 0 ? true:false;           

return num % 2 != 0;           
【JavaSE】Java方法練習題

2 ) 根據行、列、字元列印 對應行數和列數的字元(

#

),比如:行:

4

,列:

4

,字元

#

,則列印相應的效果

####
    ####
    ####
    ####           

1.方法的傳回類型 void

  1. 方法的名字 print
  2. 方法的形參 (int row, int col, char c)
  3. 方法體 , 循環
public class MethodExercise01 {
    public static void main(String[] args) {
        AA a = new AA();
        a.print(4,4,'#');
    }
}

class AA1{
    public void print(int row,int col,char c){
            for (int i = 0; i < row; i++){
                for (int j = 0; j < col;j++){//輸出每一行
                    System.out.print(c);
                }
                System.out.println();//換行
            }
}           
【JavaSE】Java方法練習題