精簡版計算機的實現
阿新 • • 發佈:2021-10-15
設計思路:
-
先寫出加減乘除四個方法;
-
利用控制檯輸入資料和運算 符號;
-
利用迴圈和switch互動寫出呼叫
-
傳遞資料
-
進行運算
程式碼如下:
package com.wang.method;
import java.util.Scanner;
public class Demo07 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入運算數字以及運算子:");
while(scanner.hasNextDouble()){
double a=scanner.nextDouble();
double b=scanner.nextDouble();
String symbol=scanner.next();
switch (symbol){
case "+":add( a,b);
break;
case "-":cut( a,b);
break;
case "*":ride( a,b);
break;
case "/":divide( a,b);
break;
default:
System.out.println("輸入符號無效:");
}
System.out.println("輸入任意字母退出");
}
scanner.close();
}
public static void add(double a,double b){
System.out.println(a+"+"+b+"="+(a+b));
}
public static void cut(double a,double b){
System.out.println(a+"-"+b+"="+(a-b));
}
public static void ride(double a,double b){
System.out.println(a+"*"+b+"="+(a*b));
}
public static void divide(double a,double b){
if(b==0){
System.out.println("分母不能為0");
}else{
System.out.println( a +"/"+b+"="+(a/b));
}
}
}