dimanche 31 mars 2019

How do you get this if/else statement to print out the method call in this java project? [duplicate]

This question already has an answer here:

I'm making a simple calculator program that allows the user to input the function they (adding, subtracting, multiplying, or division) and put in the first and second number of their equation. I've got all of the methods for adding, subtracting and whatnot but I have one problem on my hands and that's creating an if-else statement in the main method that prints out the result of the chosen function.

Here's the code:

import static java.lang.System.*;
import java.util.*;

public class calculator1
{
    public static void main(String[] args)
    {
        Calculator ti_83 = new Calculator();
        Scanner scan = new Scanner(in);

        out.print("Do you want to add, subtract, multiply or divide?: ");
        String function = scan.nextLine();

        out.print("Type in the first number you want to " + function + ": ");
        double num1 = scan.nextDouble();

        out.print("Type in the second number you want to " + function + ": ");
        double num2 = scan.nextDouble();

        if(ti_83.whatFunction(function) == "add")
            out.print("\nFinal sum:\n");
            out.println(ti_83.addition(num1, num2));

        else if(ti_83.whatFunction(function) == "subtract")  // <------- this is where I get the error
            out.print("\nFinal difference:\n");
            out.println(ti_83.subtraction(num1, num2) + "\n");


    }
}

class Calculator
{
    String math = null;
    double add, sub, multiply, divide;

    String whatFunction(String func)
    {
        if(func.equalsIgnoreCase("add") || func.equalsIgnoreCase("a"))
            math = "add";
        else if(func.equalsIgnoreCase("subtract") || func.equalsIgnoreCase("s"))
            math = "subtract";
        else if(func.equalsIgnoreCase("multiply") || func.equalsIgnoreCase("m"))
            math = "multiply";
        else if(func.equalsIgnoreCase("divide") || func.equalsIgnoreCase("d"))
            math = "divide";
        return math;
    }

    double addition(double n1, double n2)
    {
        add = n1 + n2;
        return add;
    }

    double subtraction(double n1, double n2)
    {
        if(n1 > n2)
            sub = n1 - n2;
        else
            sub = n2 - n1;
        return sub;
    }

    double multiplication(double n1, double n2)
    {
        multiply = n1 * n2;
        return multiply;
    }

    double division(double n1, double n2)
    {
        if(n1 > n2)
            divide = n1 / n2;
        else
            divide = n2 / n1;
        return divide;
    }

}

An explanation as to why this if-else statement isn't running would be appreciated.

Aucun commentaire:

Enregistrer un commentaire