返回列表 發帖

物件導向基礎概念 (五)

本帖最後由 tonyh 於 2013-9-6 20:55 編輯
  1. import java.lang.System;
  2. import java.util.Scanner;
  3. public class ch75   //主類別
  4. {
  5.     public static void main(String args[])     //主函式 (主方法)
  6.     {
  7.          int x,y;
  8.          MyMath m=new MyMath();  //於 MyMath 類別下新增 m 這個物件
  9.          Scanner s=new Scanner(System.in);
  10.          //於 Scanner 類別下新增 s 這個物件, 在新增該物件時, 需要 System 類別中的 in 物件
  11.          System.out.print("請輸入第一個數: "); //System類別中, out這個物件, 的 print()函式
  12.          x=s.nextInt();  //s 物件裡的 nextInt() 函式
  13.          System.out.print("請輸入第二個數: ");
  14.          y=s.nextInt();
  15.          System.out.println(x+"的"+y+"次方為"+m.pow(x,y));
  16.          System.out.println(x+"減去"+y+"等於"+m.minus(x,y));
  17.          System.out.println(x+"加上"+y+"等於"+m.plus(x,y));
  18.     }
  19. }

  20. class MyMath    //自訂MyMath類別, 並宣告該類別中的三個方法
  21. {
  22.     public static float pow(int a, int b)
  23.     {
  24.          int result=1;
  25.          for(int i=1; i<=b; i++)
  26.              result=result*a;
  27.          return result;
  28.     }
  29.     public static int minus(int a, int b)
  30.     {
  31.          return a-b;
  32.     }
  33.     public static int plus(int a, int b)
  34.     {
  35.          return a+b;
  36.     }
  37. }
複製代碼

返回列表