Java用面向物件實現加減乘除
阿新 • • 發佈:2019-02-15
import java.util.Scanner;
class MyMath{
public int add(int a,int b){
return a + b;
}
public int sub(int a,int b){
return a - b;
}
public int mul(int a,int b){
return a * b;
}
public int div(int a,int b){
return a / b;
}
}
class MyMathTest{
public static void main(String[] args){
//建立鍵盤錄入物件
Scanner sc = new Scanner(System.in);
System.out.println("請輸入第一個運算元:");
int firstNumber = sc.nextInt();
System.out.println("請輸入第二個運算元:");
int secondNumber = sc.nextInt();
//建立MyMath物件並使用
MyMath mm = new MyMath();
System.out.println("加法結果:" + mm.add(firstNumber,secondNumber));
System.out.println("減法結果:" + mm.sub(firstNumber,secondNumber));
System.out.println("乘法結果:" + mm.mul(firstNumber,secondNumber));
System.out.println("除法結果:" + mm.div(firstNumber,secondNumber));
}
}
執行結果截圖: