简体   繁体   中英

Java int calculator: re-use a calculated value for further calculation

I developed a simple calculator using integers (no GUI), which is working fine. The calculator deploys seven types of calculation. Goals and achievements listed below.

The goals are:

  • calculation with all of the types of calculation (done)
  • deploy options for continuing calculation, switching operators, exit (done)
  • deploy an option continuing with a calculated result (work in progress)

I was wondering how I could use a calculated result for another calculation . I tried to store the variable for a specific result in the corresponding switch-case-options, which is implemented in the MySimpleIntCalculatorHelper class (code's down below with documentation). Unfortunately this throws an error and prevents the calculator from working properly. Is there any advice which one you can tell me? Maybe I oversee something quite obvious!

For any further information about the source code, I'll leave you the link to my GitHub repository if necessary. https://https://github.com/DarkPalad1n/ExamPreCondition/tree/master/src

Thank you in advance!

Kind regards, Passi

import java.util.Scanner;

/**
 * This class is as an extension of the class MySimpleIntCalculatorAdvanced.
 *
 * It inherits methods from its parental class and deploys useful methods for
 * running the calculator itself.
 *
 * @author DarkPalad1n
 *
 */

public class MySimpleIntCalculatorHelper extends MySimpleIntCalculatorAdvanced {

    static Scanner scanObject = new Scanner(System.in);
    static MySimpleIntCalculatorHelper erg = new MySimpleIntCalculatorHelper();
    static int operator = scanObject.nextInt();
    static int numberOne, numberTwo, numberOneAd;
    static String continueOption;

    // ---------------------CONSTRUCTOR--------------------

    public MySimpleIntCalculatorHelper() {

        chooseOperator();
    }

    // --------------------METHODS--------------------

    /**
     * User enters the menu. User's able to choose between seven operations.
     */
    public static void chooseOperator() {

        System.out.println(
                "Please enter your operator of choice: \n1.Addition \n2.Subtraction \n3.Multiplication \n4.Division \n5.Remainder \n6.Sum \n7.Checksum \n0.Exit");

    }

    /**
     * Method is used to take the user's figure inputs.
     *
     * The condition checks first whether the operator is 0 or 7 before entering the
     * cases where two figures are required.
     *
     * Case 0 ends the calculation.
     *
     * Case 7 only needs one input, which is why the method checks beforehand the
     * chosen case to take the correct input.
     */
    public static void chooseNumberOneAndTwo() {

        if (operator == 0) {
            System.out.println("Thank you for participating!");
            System.exit(0);
        } else if (operator == 7) {
            System.out.println("Please enter your number:");
            numberOneAd = scanObject.nextInt();
        } else {
            System.out.println("Please enter your first number:");
            numberOne = scanObject.nextInt();
            System.out.println("Please enter your second number:");
            numberTwo = scanObject.nextInt();

        }

    }

    /**
     * Method is used to perform mathematical operations in conjunction with the
     * chosen operator.
     */
    public static void performCalculation() {

        switch (operator) {
            case 1:
                erg.add(numberOne, numberTwo);
                break;
            case 2:
                erg.sub(numberOne, numberTwo);
                break;
            case 3:
                erg.mult(numberOne, numberTwo);
                break;
            case 4:
                erg.div(numberOne, numberTwo);
                break;
            case 5:
                erg.mod(numberOne, numberTwo);
                break;
            case 6:
                erg.sum(numberOne, numberTwo);
                break;
            case 7:
                erg.quer(numberOneAd);
                break;
            case 0:
                System.out.println("Thank you for participating!");
                System.exit(0);
            default:
                System.out.println("Unsupported operator. Please retry.");

        }

    }

    /**
     * This method asks the user whether to continue another calculation or not.
     *
     * scanObject.nextLine(); consumes the leftovers \n from .nextInt();. After
     * this workaround continueOption is ready for the user's input.
     */
    public static void continueCalculationOption() {

        System.out.println("Would you like to continue? \n Enter Y to continue. \n Enter N to exit. \n Enter S to switch the operator.");
        scanObject.nextLine();
        continueOption = scanObject.nextLine();
    }

    /**
     * Method is used to perform the users input from continueCalculationOption();.
     *
     * By entering "Y" the user is redirected to chooseNumberOneAndTwo(); to enter
     * new figures for calculation with the same operator.
     *
     * By entering "N" the user is going to exit the calculator.
     *
     * By entering "S" the user is able to switch the operator. It is important to
     * assign (zuweisen) operator to scanObject.nextInt(); for a proper performance
     * of the new operator input.
     */
    public static void performContinueCalculationOption() {

        switch (continueOption) {
            case "Y":
                System.out.println("Continue.");
                chooseNumberOneAndTwo();
                break;
            case "N":
                System.out.println("Thank you for participating.");
                System.exit(0);
                break;
            case "S":
                System.out.println("Switch operator.");
                chooseOperator();
                operator = scanObject.nextInt();
                break;
        }

    }

    /**
     * Method is used to perform at least a sequence of three instructions
     * while continueOption is equal to "Y".
     */
    public static void performCalculationSequence() {

        do {
            performCalculation();
            continueCalculationOption();
            performContinueCalculationOption();
        } while (continueOption.equals("Y"));
    }

    /**
     * This method uses a sequence of the helping methods created in this class
     * to run all the functionalities the calculator offers. The method runs in
     * the main method of the corresponding class.
     *
     * It consists of chooseNumberOneAndTwo(); and performCalculationSequence();.
     * There is a condition if the user's input equals "S" the user is able to
     * switch operators. After this particular method was used and the new
     * operator was selected, new figures are required and the calculation will
     * be performed. run(); will be executed continuously as long as a different
     * operator is chosen or "N" is entered.
     *
     */
    public static void run() {

        chooseNumberOneAndTwo();
        performCalculationSequence();
        if (continueOption.equals("S")) {
            chooseNumberOneAndTwo();
            performCalculationSequence();
            run();
        } else {
            System.out.println();
        }
    }
}

You can add a static attribute to your class and save your result in it. To choose the number, you could modify chooseNumberOneAndTwo() to make it accepting a command to choose the last result instead. (like "Ans" )

To detect this, you must change scanObject.nextInt() to scanObject.next() . To check if it is a number, you can use numberOne.matches("-?\\d+") . Explanation:

  • -?: first character is '-'; ? means it is optional (for negative integers)
  • \\d: \d means a digit character; '\' is \\ in code
  • +: there are 1 or more of the previous character

The completed method could be like this (previousResult is the static attribute to save the last result):

public static void chooseNumberOneAndTwo() {

    String inp;

    if (operator == 0) {
        System.out.println("Thank you for participating!");
        System.exit(0);
    } else if (operator == 7) {
        System.out.println("Please enter your number:");
        inp = scanObject.next();
        if (inp.matches("-?\\d+")) {
            numberOneAd = Integer.parseInt(inp);
        }
        else if (inp.matches("Ans")) {
            numberOneAd = previousResult;
        }
        else {}//Invalid input
    } else {
        System.out.println("Please enter your first number:");
        inp = scanObject.next();
        if (inp.matches("-?\\d+")) {
            numberOne = Integer.parseInt(inp);
        }
        else if (inp.matches("Ans")) {
            numberOne = previousResult;
        }
        else {}//Invalid input
        System.out.println("Please enter your second number:");
        inp = scanObject.next();
        if (inp.matches("-?\\d+")) {
            numberTwo = Integer.parseInt(inp);
        }
        else if (inp.matches("Ans")) {
            numberTwo = previousResult;
        }
        else {}//Invalid input

    }

}

I'd also suggest you to create a new method for this as this method does the same thing 3 times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM