GraiL
GraiL

Reputation: 23

Java use user input from other methods

I visited other questions similar to mine but did not find the one that is applicable to me.

To lessen my line of codes instead of copy pasting that input process to my if else statement. I created a UInputs(); method that will get user inputs. So I can just call it whenever it is needed but i cant use the user inputted values inside UInputs().

import java.util.Scanner;

public class Calculator {
    public static void UInputs(){
        double num1, num2, num3, num4, num5;
        Scanner scan = new Scanner(System.in);
        System.out.print("1st Number: ");
        num1 = scan.nextDouble();
        System.out.print("2nd Number: ");
        num2 = scan.nextDouble();
        System.out.print("3rd Number: ");
        num3 = scan.nextDouble();
        System.out.print("4th Number: ");
        num4 = scan.nextDouble();
        System.out.print("5th Number: ");
        num5 = scan.nextDouble();
    }

    
    public static void main (String[] args){
    char Choice;
    double num1, num2, num3, num4, num5;

    System.out.println("\t_________________________________\n");
    System.out.println("\t|\tMATH OPERATIONS\t\t|\n\t|\t[+]\tAddition\t|\n\t|\t[-]\tSubtraction\t|\n\t|\t[*]\tMultiplication\t|\n\t|\t[/]\tDivision\t|\n");
    System.out.println("\t|_______________________________|\n");
    System.out.print("\nEnter you Choice: ");
    Scanner scan = new Scanner(System.in);
    Choice = scan.nextLine().charAt(0);

    if ( Choice == '+') {//ADDITION
        System.out.println("================================\nAddition\n");
        UInputs();
        double answer = num1 + num2 + num3 + num4 + num5;
        System.out.println("\nSum : " + answer );
        System.out.println("================================\n");
    }
    else if (Choice == '-') {//SUBTRACTION
        System.out.println("================================\nSubtraction\n");
        System.out.print("1st Number: ");
        num1 = scan.nextDouble();
        System.out.print("2nd Number: ");
        num2 = scan.nextDouble();
        System.out.print("3rd Number: ");
        num3 = scan.nextDouble();
        System.out.print("4th Number: ");
        num4 = scan.nextDouble();
        System.out.print("5th Number: ");
        num5 = scan.nextDouble();
        double answer = num1 - num2 - num3 - num4 - num5;
        System.out.println("\nDifference : " + answer );
        System.out.println("================================\n");
    }

Upvotes: 0

Views: 99

Answers (2)

Rob Evans
Rob Evans

Reputation: 2874

Not the best answer I could have come up with but certainly some improvements to make the code easier to digest...

I changed UInputs to a method called calculate(). It now takes the function selected as input and then asks the user for 5 numbers. The function is then applied to the 5 numbers. Another way to perform this calculation would be to request a number from the user, return it, and sequentially apply the function to the returned number(s) to get a result... this would be nicer.

import java.util.Scanner;

public class Calculator {
    private static final Scanner scan = new Scanner(System.in);

    /**
    * My initial thought here was that UInputs should return values
    * and these should be cumulatively totalled. 
    * There's no need to hold the inputs in memory since 
    * once they're consumed, they're not longer needed.
    */
    public static double calculate(char functionToApply) {
        double[] inputs = new double[5];

        // works for number of inputs up to 20 - could just print "number i: " here for simplicity. 
        for (int i=0; i<inputs.length; i++) {
            String promptMessage = (i+1) + "";  // number
            // postfixture (st, nd, rd, th)
            switch (i+1) {
                case 1: promptMessage = promptMessage+"st"; break;
                case 2: promptMessage = promptMessage+"nd"; break;
                case 3: promptMessage = promptMessage+"rd"; break;
                default: promptMessage = promptMessage+"th"; break;
            }
            System.out.print(promptMessage + " Number: ");
            inputs[i] = scan.nextDouble();
        }

        double result = 0;
        for (int i=0; i<inputs.length; i++) {
            switch (functionToApply) {
                case '+': result = result + inputs[i]; break;
                case '-': result = result - inputs[i]; break;
            }
        }
        return result;
    }

    public static void main(String[] args) {

        displayMenu();
        
        char function;
        System.out.print("\nEnter your Choice: ");
        function = scan.nextLine().charAt(0);

        String heading = "";
        String lineLabel = "";
        switch (function) {
            case '+':
                heading = "Addition";
                lineLabel = "Sum";
                break;
            case '-':
                heading = "Subtraction";
                lineLabel = "Difference";
                break;
        }

        System.out.println("================================\n" + heading + "\n");
        System.out.println("\n" + lineLabel + " : " + calculate(function));
        System.out.println("================================\n");
    }

    private static void displayMenu() {
        System.out.println("\t_________________________");
        System.out.println("\t|\tMATH OPERATIONS\t\t|");
        System.out.println("\t|\t[+]\tAddition\t\t|");
        System.out.println("\t|\t[-]\tSubtraction\t\t|");
        System.out.println("\t|\t[*]\tMultiplication\t|");
        System.out.println("\t|\t[/]\tDivision\t\t|");
        System.out.println("\t|_______________________|\n");
    }
}

This should be easier for you to extend/edit though.

Output:

    _________________________
    |   MATH OPERATIONS     |
    |   [+] Addition        |
    |   [-] Subtraction     |
    |   [*] Multiplication  |
    |   [/] Division        |
    |_______________________|


Enter your Choice: +
================================
Addition

1st Number: 1
2nd Number: 2
3rd Number: 3
4th Number: 4
5th Number: 5

Sum : 15.0
================================


Process finished with exit code 0

Similarly for subtraction:


Enter your Choice: -
================================
Subtraction

1st Number: 10
2nd Number: 9
3rd Number: 1
4th Number: 0
5th Number: 0

Difference : -20.0
================================

Upvotes: 1

Oleh Kurpiak
Oleh Kurpiak

Reputation: 1369

you can create some kind of wrapper class

class MyNumberWrapper {

  double num1;
  double num2;

}

then UInput will look like this

public static MyNumberWrapper UInputs(){
    MyNumberWrapper wrapper = new MyNumberWrapper();
    Scanner scan = new Scanner(System.in);
    System.out.print("1st Number: ");
    wrapper.num1 = scan.nextDouble();
    System.out.print("2nd Number: ");
    wrapper.num2 = scan.nextDouble();
    return wrapper;
}

then in your main function you can just use MyNumberWrapper wrapper = UInput() and access all variables with wrapper.num1, wrapper.num2 etc

Upvotes: 0

Related Questions