1. 程式人生 > >java程式碼例項 使用switch實現簡易的計算器(實現加減乘除)

java程式碼例項 使用switch實現簡易的計算器(實現加減乘除)

import java.util.Scanner;

/*
 * 使用switch實現簡易的計算器(實現加減乘除); 
 */
public class test {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("輸入一個表示式(例如: 5 + 3):");
		int a = sc.nextInt();
		char ch = sc.next().charAt(0);
		int b = sc.nextInt();
		switch (ch) {
		case '+':
			jia(a, b);
			break;
		case '-':
			jian(a, b);
			break;
		case '*':
			cheng(a, b);
			break;
		case '/':
			chu(a, b);
			break;
		default:
			System.out.println("輸入錯誤");
			break;
		}
	}

	private static void cheng(int a, int b) {
		int sum = a * b;
		System.out.println("兩數積:" + sum);
	}

	private static void jian(int a, int b) {
		int sum = a - b;
		System.out.println("兩數差:" + sum);
	}

	private static void chu(int a, int b) {
		if (b == 0) {
			System.out.println("除數不能為零~");
		} else {
			int sum = a / b;
			System.out.println("兩數商:" + sum);
		}
	}
	private static void jia(int a, int b) {
		int sum = a + b;
		System.out.println("兩數和:" + sum);
	}
}