【練習題】構造方法 編寫Java程式,模擬簡單的計算器。
阿新 • • 發佈:2019-02-09
package day09; /*1.【練習題】構造方法 編寫Java程式,模擬簡單的計算器。 定義名為Number的類,其中有兩個整型資料成員n1和n2,應宣告為私有。編寫構造方法,賦予n1和n2初始值,再為該類定義加(addition)、減(subtration)、乘(multiplication)、除(division)等公有成員方法,分別對兩個成員 變數執行加、減、乘、除的運算。 在main方法中建立Number類的物件,呼叫各個方法,並顯示計算結果。 */ public class HomeWork_01 { public static void main(String[] args) { // Number s1 = new Number(); //備註掉的是無參構造部分,成員方法改void,不要return,改out輸出 Number s1 = new Number(5,1); // s1.setN1(5); // s1.setN2(1); int sum = s1.addition(); int div = s1.division(); int sub = s1.subtration(); int mul = s1.multiplication(); System.out.println("和為:" + sum + ",相減為:" + sub + ",相乘為:" + mul + ",相除為:" + div); } } class Number { private int n1; private int n2; public Number(int n1 ,int n2){ this.n1 =n1; this.n2 =n2; //不加this會導致 //Unresolved compilation problem:未編譯的問題: //The constructor Number() is undefined 建構函式號()沒有定義 } // public int getN1() { // return n1; // } // // public void setN1(int n1) { // this.n1 = n1; // } // // public int getN2() { // return n2; // } // // public void setN2(int n2) { // this.n2 = n2; // } // // public Number() { // this.n1 = 0; // this.n2 = 0; // } public int addition() { return n1 + n2; } public int subtration() { return n1 - n2; } public int multiplication() { return n1 * n2; } public int division() { return n1 / n2; } }