Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Arithmetic demo for El Camino High School AP Computer Science
- import java.util.Scanner;
- public class Arithmetic {
- public static char ADD = '+';
- public static char SUBTRACT = '-';
- public static char MULTIPLY = '*';
- public static char DIVIDE = '/';
- public static char MODULUS = '%';
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- // Get input.
- System.out.print("Enter first number: ");
- double first = input.nextDouble();
- System.out.print("Enter operation: ");
- char operation = getOperation(input);
- System.out.print("Enter second number: ");
- double second = input.nextDouble();
- // Perform operation.
- System.out.print("Result: ");
- if (operation == ADD) {
- System.out.println(first + second);
- } else if (operation == SUBTRACT) {
- System.out.println(first - second);
- } else if (operation == MULTIPLY) {
- System.out.println(first * second);
- } else if (operation == DIVIDE) {
- System.out.println(first / second);
- } else if (operation == MODULUS) {
- System.out.println(first % second);
- } else {
- // This should not happen. Why?
- }
- }
- public static char getOperation(Scanner input) {
- // Get operation. from user.
- char operation = input.next().charAt(0);
- if (operation == ADD
- || operation == SUBTRACT
- || operation == MULTIPLY
- || operation == DIVIDE
- || operation == MODULUS) {
- // If operation is valid, return.
- return operation;
- } else {
- // Operation is invalid, so try again.
- System.out.println("Invalid operation. Try again.");
- return getOperation(input);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement