Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package me.scott.assignment;
- import java.util.Scanner;
- /*
- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- Training: Create a simple 4 operation calculator in JAVA
- Date: 2019-11-27
- Author: Scott Hammontree
- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- */
- public class Calculator {
- public static void main(String[] args) {
- Calculator calc = new Calculator();
- calc.listen();
- }
- private void listen() {
- System.out.println("Simple Calculator is active. \n" +
- "Please enter a simple equation using a whole number.\n" +
- "with one of the following operators [+|-|*|/]\n" +
- "e.g.[ 12 + 2 | 12 - 2 | 12 * 2 | 9 / 3]\n" +
- "e.g. number operator number with spaces included\n");
- Scanner scanner = new Scanner(System.in);
- while (true) {
- // asking for user input
- System.out.println("Waiting for input....");
- // variable to store the command.
- String command = "";
- // wait for user input
- command = scanner.nextLine();
- // Leave on exit
- if (command.equals("exit") || command.toUpperCase().equals("EXIT")) {
- break;
- } else {
- // Put the equation elements into a string array [0,1,2]
- // Splits this string around matches of the given regular expression i.e. " ".
- String[] args = command.split(" ");
- if (args.length != 3) {
- System.out.println("Invalid syntax. \n" +
- "Correct syntax is [number operator number] including spaces" +
- "e.g. -> 1 + 2");
- // 'continue' is unnecessary as the last statement in a loop.
- // I use continue to return to the top of the loop and skip further processing.
- continue;
- }
- // Check the 1st and 3rd string arg. IsNumeric()?
- double firstNumber, secondNumber;
- try {
- firstNumber = Double.parseDouble(args[0]);
- secondNumber = Double.parseDouble(args[2]);
- } catch (NumberFormatException ex) {
- System.out.println("Please enter a whole numbers eg: [3 | 4 | 12].");
- System.out.println("ERROR: one of the arguments is not a valid number ");
- System.out.println("ERROR: " + ex);
- continue;
- }
- // CHECK for DIVIDE by ZERO
- if (secondNumber == 0) {
- System.out.println("Cannot DIVIDE by ZERO!!");
- continue;
- }
- // Check the operators and calculate appropriate result.
- switch (args[1]) {
- case "+":
- System.out.println("Result: " + (firstNumber + secondNumber));
- break;
- case "-":
- System.out.println("Result: " + (firstNumber - secondNumber));
- break;
- case "*":
- System.out.println("Result: " + (firstNumber * secondNumber));
- break;
- case "/":
- System.out.println("Result: " + (firstNumber / secondNumber));
- break;
- default:
- System.out.println("Operator not recognized!");
- break;
- } // END SWITCH
- } // END IF
- } // END of scanner loop
- System.out.println("Calculator is shutting down.\nGood bye.");
- } // END of listen
- } // END of class
Advertisement
Add Comment
Please, Sign In to add comment