mercredi 28 septembre 2016

I am trying to build a basic calculator using if statements

I am trying to make a basic calculator for class I came up with the code below but all it does it addition. even if I use -, *, or /. Any tips?

Scanner input = new Scanner(System.in); String num1, num2, operation, function;

    System.out.println("Enter a simple equation: ");
    function = input.nextLine();
    int firstspace = function.indexOf(" ");
    num1 = (function.substring(0,firstspace));
    int lastspace = function.lastIndexOf(" ");
    operation = (function.substring(firstspace,lastspace));
    num2= (function.substring(lastspace+1,function.length()));
    double n1 = Double.parseDouble(num1);
    double n2 = Double.parseDouble(num2);



    if (operation.equals(" + "));
    {
        System.out.println("your answer is " + (n1 + n2));
    }
    if  (operation.equals(" - "))
    {
        System.out.println("your answer is " + (n1 - n2));
    }

    if (operation.equals(" / "))
    {
        System.out.println("your answer is " + (n1 / n2));
    }
    if (operation.equals(" * "))
    {
        System.out.println("your answer is " + ( n1*n2));
    }

}

}

Aucun commentaire:

Enregistrer un commentaire