1. 程式人生 > >1133-C/C++經典程式訓練3---模擬計算器-JAVA

1133-C/C++經典程式訓練3---模擬計算器-JAVA

C/C++經典程式訓練3---模擬計算器

Time Limit: 1000 ms Memory Limit: 8192 KiB

Problem Description

簡單計算器模擬:輸入兩個整數和一個運算子,輸出運算結果。

Input

第一行輸入兩個整數,用空格分開;
第二行輸入一個運算子(+、-、*、/)。
所有運算均為整數運算,保證除數不包含0。

Output

輸出對兩個數運算後的結果。

Sample Input

30 50
*

Sample Output

1500

Hint

Source

import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int a = scanner.nextInt();
		int b = scanner.nextInt();
		String c = scanner.next();
		char m = c.charAt(0);
		if (m == '+') {
			System.out.println(a + b);
		} else if (m == '-') {
			System.out.println(a - b);
		} else if (m == '*') {
			System.out.println(a * b);
		} else if (m == '/') {
			System.out.println(a / b);
		} else {
			return;
		}
	}
}

  or

import java.util.*;

class Calculate {
	int a, b;

	public Calculate(int a, int b) {
		this.a = a;
		this.b = b;
	}

	int add() {
		return a + b;
	}

	int less() {
		return a - b;
	}

	int multiply() {
		return a * b;
	}

	int except() {
		return a / b;
	}
}

public class Main {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNext()) {
			int a = scanner.nextInt();
			int b = scanner.nextInt();
			String string = scanner.next();
			char c = string.charAt(0);
			Calculate calculate = new Calculate(a, b);
			switch (c) {
			case '+':
				System.out.println(calculate.add());
				break;
			case '-':
				System.out.println(calculate.less());
				break;
			case '*':
				System.out.println(calculate.multiply());
				break;
			case '/':
				System.out.println(calculate.except());
				break;
			default:
				break;
			}
		}
	}
}