【练习题】构造方法 编写Java程序,模拟简单的计算器。
生活随笔
收集整理的這篇文章主要介紹了
【练习题】构造方法 编写Java程序,模拟简单的计算器。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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;}}
總結
以上是生活随笔為你收集整理的【练习题】构造方法 编写Java程序,模拟简单的计算器。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一维数组工具 OneArryasTool
- 下一篇: [基础题] 5.(*)按如下要求编写Ja