Create your simple java calculator

Without directly giving me the answer can someone help me with this simple calculator that I am trying to write? Everything seem to work well except for the very end when I ask the user to make a choice for add,subtract, multiply, or divide. It does not allow me to enter my choices in the console. I think it has something to do with the array of String that I created and the if statement. Not sure. Any tips would be much appreciated.

Scanner input method

Used eclipse IDE

import java.util.Scanner;

public class simpleCalculator {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        //declare my variables
        int firstNum;
        int secondNum;
        int division = 0, addition = 0, subtraction = 0, multiplication = 0;
        String userChoice = "";
        String choices[] = {"add","multiply","divide","subtract"};

        //ask for user input
        System.out.print("Please enter first number: ");
        firstNum = input.nextInt();
        System.out.print("Please enter second number: ");
        secondNum = input.nextInt();
        System.out.println("What type of operation would you like to perform on these numbers?");
        System.out.println("add " +"multiply " +"subtract " + "divide ");
        userChoice = input.nextLine();

        if (userChoice == "add"){
                    System.out.print("Answer = " + addition);
        }


        //calculator formulas
        addition = firstNum + secondNum;
        multiplication = firstNum * secondNum;
        subtraction = firstNum - secondNum;
        division = firstNum / secondNum;

    }

}

if you find bugs fix with these lines
just add another input.nextLine() before userChoice = input.nextLine(); and to compare String, use userChoice .equals(“add”)


to continue your program running for different inputs use a while loop – while(input.hasNext(){ //your code}


Try using instead of input.nextLine() use input.next()


Also make sure you perform the addition in a separate function, because you are only printing the value 0 right now, no matter what number you input


I would further simplify your compute function by returning directly:

public static double compute(double num1, char operator, double num2) { switch(operator) { case '+': return num1 + num2;
case '-': return num1 - num2;
	case 'x': return num1 * num2; 
	case '/': return num1 / num2;
	case '%': result = num1 % num2;

} 
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s