Simple Calculator - If statement - java

I am new to java and programming.
Can someone suggest what can be used so that the answer must equal to +,-,*,/ ? At the moment I am trying to create an if statement but I am getting an error and I am not quite sure why. Can someone look at my code and help me complete the if statement please? If you have any other suggestions on what can be improved, please share.
import java.util.Scanner;
public class Calculator {
public static void main (String Args []) {
Scanner input = new Scanner(System.in);
double firstNumber, secondNumber;
String equationOperator;
System.out.println("Please give your first number: \t");
firstNumber = input.nextDouble();
System.out.println("Please give your second number: \t");
secondNumber = input.nextDouble();
System.out.println("Which equation would you like to perform?");
System.out.println("Please enter one of the following + - / * \t");
equationOperator = input.next();
switch (equationOperator) {
case "+":
System.out.println("Your chosen equation is: Adding");
System.out.println("Your answer is: " + (firstNumber + secondNumber));
break;
case "-":
System.out.println("Your chosen equation is: Subtracting");
System.out.println("Your answer is: " + (firstNumber - secondNumber));
break;
case "/":
System.out.println("Your chosen equation is: Dividing");
System.out.println("Your answer is: " + (firstNumber / secondNumber));
break;
case "*":
System.out.println("You chosen equation is: Multiplying");
System.out.println("Your answer is: " + (firstNumber * secondNumber));
break;
}
if (!equationOperator.equals("+ || - || / || *") {
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
System.out.println("\t Thank You for using my Calculator");
}
}

You're missing a closing parenthesis in your condition:
if (!equationOperator.equals("+ || - || / || *") {
should be
if (!equationOperator.equals("+ || - || / || *")) {
Note that this won't give you the expected result either, as you are checking for the exact string "+ || - || / || *".
You would either need several equals, e.g.
if (!equationOperator.equals("+") && !equationOperator.equals("-") ...) {
or simply use the default case in your switch statement:
switch (equationOperator) {
case "+":
System.out.println("Your chosen equation is: Adding");
System.out.println("Your answer is: " + (firstNumber + secondNumber));
break;
case "-":
System.out.println("Your chosen equation is: Subtracting");
System.out.println("Your answer is: " + (firstNumber - secondNumber));
break;
case "/":
System.out.println("Your chosen equation is: Dividing");
System.out.println("Your answer is: " + (firstNumber / secondNumber));
break;
case "*":
System.out.println("You chosen equation is: Multiplying");
System.out.println("Your answer is: " + (firstNumber * secondNumber));
break;
default:
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
The default case will be executed when none of the other matches. See the documentation for more details.

Use a default case in switch
default:
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
Also your if statement is incorrect apart from ) bracket missing from end.
if (!equationOperator.equals("+ || - || / || *")) This compares your equationOperator with string "+ || - || / || *" .
You wanted this
if (!(equationOperator.equals("+") || equationOperator.equals("-") ||
equationOperator.equals("/") || equationOperator.equals("*"))) {

Related

How do I tell my program to ignore an instruction if a certain case is true?

I'm a very beginner java coder and I'm coding a simple calculator using swing, and I want to implement square roots into the operators. I want it to be so that in the case that the operator is a square root, the calculator wont ask for the second number.
package swingcalculator;
import javax.swing.JOptionPane;
public class SwingCalculator {
public static void main(String[] args) {
double num1, num2, answer;
String operator;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first number:"));
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
switch(operator) {
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
case "*":
answer = num1 * num2;
break;
case "/":
answer = num1 / num2;
break;
case "sqrt":
answer = Math.sqrt(num1);
break;
case "^":
answer = Math.pow(num1, num2);
break;
default:
System.out.println("You have entered an invalid operator");
return;
}
if (Boolean.parseBoolean(operator) == Boolean.parseBoolean("sqrt")){
JOptionPane.showMessageDialog(null, "Square root of " + num1 + " = " + answer);
}
else{
JOptionPane.showMessageDialog(null, num1 + " " + operator + " " + num2 + " = " + answer);
}
}
Any help would be appreciated!
Put everything after the operator = line inside a conditional (you can also move the JOptionPane.showMessageDialog lines inside the appropriate block of the conditional statement, because you don't need to check operator again):
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
if (!operator.equals("sqrt")) {
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
switch (...) { ... }
JOptionPane.showMessageDialog(null, num1 + " " + operator + " " + num2 + " = " + answer);
} else {
JOptionPane.showMessageDialog(null, "Square root of " + num1 + " = " + answer);
}
operator = JOptionPane.showInputDialog("Enter your operator (+ , - , * , /, ^, sqrt):");
if(!operator.equals("sqrt"){
num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second number number:"));
}
Read the second number only if operator is not 'sqrt', however your program seems to have many anomalies, as suggested to you in comments by others

How to get calculator program to add, subtract, multiply, divide more than two numbers

I have made the basic calculator app which can add, subtract multiply or divide just two numbers. What I am trying to do improve the program to be able to '+' '-' '*' or '/' more than just two numbers. Here is the basic java calculator program I have down so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("\nEnter first number: \n");
double fnum = input.nextDouble();
System.out.println("\nEnter an operation sign such as, '+', '-', '*', or '/', '=': \n");
char operator = input.next().charAt(0);
System.out.println("\nEnter second number: \n");
double snum = input.nextDouble();
input.close();
switch(operator) {
case '+':
double answer = fnum + snum;
System.out.println("\n" + fnum + " " + operator + " " + snum + " = " + answer);
break;
case '-':
double answer1 = fnum - snum;
System.out.println("\n" + fnum + " " + operator + " " + snum + " = " + answer1);
break;
case '*':
double answer2 = fnum * snum;
System.out.println("\n" + fnum + " " + operator + " " + snum + " = " + answer2);
break;
case '/':
double answer3 = fnum / snum;
System.out.println("\n" + fnum + " " + operator + " " + snum + " = " + answer3);
break;
default:
System.out.println("Wrong choice for operator. ");
break;
}
}
}
To achieve this I was thinking that there has to be a loop probably before the sysout "Enter operator" line and I have tried to incorporate a do while loop with the while part being (operator != '=') and have had no success. Oh yeah and of coarse I need to reword the "Enter second number" sysout. Thanks in advance for any advice!
**Here's an example output of my current calculator program followed by an example of the I output of my desired calculator program.
current calculator output:
8.0 + 2.0 = 10.0
what i'm looking for calculator program to do:
8.0 - 4.0 * 10.0 = 40.0
Note: I am actively working for a solution myself when I have time to do so. If you dont feel like helping me that's perfectly fine. I think my question is clear, valid, and not necessary to delete according to the community guidelines. thanks
The code below does not implement any error checking and, more important, does not take into account the operators precedence - that's why it's better to have a parser - but can give you an idea.
the values and the operators are obtained in a loop which is valid until the user enters the = sign
the values and the operators entered are stored in the lists numbers and operators
after exiting the loop the operations are performed on the stored values
public class Calculator {
public static void main(String[] args) {
ArrayList<Double> numbers = new ArrayList<Double>();
ArrayList<Character> operators = new ArrayList<Character>();
Scanner scanner = new Scanner(System.in);
try {
do {
System.out.println("\nEnter a number: \n");
numbers.add(scanner.nextDouble());
System.out.println("\nEnter an operation sign such as, '+', '-', '*', or '/', '=': \n");
char operator = scanner.next().charAt(0);
if (operator == '=')
break;
operators.add(operator);
} while (true);
} finally {
scanner.close();
}
Double answer = numbers.remove(0);
String resultText = "" + answer;
for (int i=0; i<operators.size(); ++i) {
char operator = operators.get(i);
Double number = numbers.get(i);
switch(operator) {
case '+':
answer += number;
break;
case '-':
answer -= number;
break;
case '*':
answer *= number;
break;
case '/':
answer /= number;
break;
default:
System.out.println("Wrong choice for operator. ");
break;
}
resultText += " " + operator + " " + number;
}
System.out.println("\n" + resultText + " = " + answer);
}
}

Java Simple English Calculator, output issue

I am writing a calculator program that takes inputs from 0-9 and outputs the results in both numerical from and in plain english (Ex: Two plus three equals 5). I have gotten it to be able to print out the result in words but I am now stuck on how to get it to print out the original problem in numerical form. The output must include both the result in numbers and in words.
The numbers have already been converted into strings through a switch statement but is there anyway I can print out the original problem? If not would I have to completely restructure this instead? Any help would be appreciated I have been stuck on this for a while now.
Here is my code
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operation;
int num1, num2;
//Asks for user to input first number
System.out.println("Please enter the first number (0-9)");
num1 = input.nextInt();
//Asks user for an operation
System.out.println("Please enter the type of operation that you would like to perform");
operation = input.next().charAt(0);
//Asks user to input the second number
System.out.println("Please enter the second number (0-9)");
num2 = input.nextInt();
//Limits the numbers to the range of 0-9
if(num1 > 9 || num2 > 9){
System.out.println("Invalid Digit!!");
System.exit(0);}
//An array that converts number into a string
String num[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
break;
case '/': //Division conversion
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
break;
case '^': //Exponentiation conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;}
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
break;
default:
System.out.println("Error: Invalid Operation Entered"); }
}
}
Its very simple, I think you are getting confused. Consider following points:
You have original numbers saved in num1 and num2, so if you want to show the original numbers in integer form, then just use num1 instead of num[num1]
You are checking for zero division when finding exponent. You should shift this check to division case.
Replace your switch like this:
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" - "+num2 + " = " + (num1-num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" + "+num2 + " = " + (num1+num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
System.out.println(num1+" * "+num2 + " = " + (num1*num2));
break;
case '/': //Division conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;
}
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
System.out.println(num1+" / "+num2 + " = " + (num1/num2));
break;
case '^': //Exponentiation conversion
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
System.out.println(num1+" ^ "+num2 + " = " + Math.pow(num1,num2));
break;
default:
System.out.println("Error: Invalid Operation Entered");
}
See if the below print statements helps
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" "+operation + " "+num2+ "="+(num1 - num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" "+operation + " "+num2+ "="+(num1 + num2));
break;
is it this what you are looking for? for example for 9 + 9 your output will be:
nine plus nine is 18 9 + 9 = 18
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operation;
int num1, num2;
//Asks for user to input first number
System.out.println("Please enter the first number (0-9)");
num1 = input.nextInt();
//Asks user for an operation
System.out.println("Please enter the type of operation that you would like to perform");
operation = input.next().charAt(0);
//Asks user to input the second number
System.out.println("Please enter the second number (0-9)");
num2 = input.nextInt();
//Limits the numbers to the range of 0-9
if(num1 > 9 || num2 > 9){
System.out.println("Invalid Digit!!");
System.exit(0);}
//An array that converts number into a string
String num[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
switch(operation){
case '-': //Subtraction conversion
System.out.println(num[num1]+" minus "+num[num2] + " is " + (num1-num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 - num2));
break;
case '+': //Addition conversion
System.out.println(num[num1]+" plus "+num[num2] + " is " + (num1+num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 + num2));
break;
case '*': //Multipication conversion
System.out.println(num[num1]+" multiplied by "+num[num2] + " is " + (num1*num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 * num2));
break;
case '/': //Division conversion
System.out.println(num[num1]+" divided by "+num[num2] + " is " + (num1/num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(num1 / num2));
break;
case '^': //Exponentiation conversion
if(num2 == 0){ //checks to see if the second number entered is 0
System.out.println("Error: Cannot divide by Zero"); //Divide by Zero error message
break;}
System.out.println(num[num1]+" to the power of "+num[num2] + " is " + Math.pow(num1,num2));
System.out.println(num1+" "+operation + " "+num2+ " = "+(Math.pow(num1,num2)));
break;
default:
System.out.println("Error: Invalid Operation Entered"); }
}
}

Simple syntax error

import java.io.PrintStream;
import java.util.Scanner;
public class BasicCalculator
{
public static void main(String[] args)
{
int ADDITION = 1;
int SUBTRACTION = 2;
int MULTIPLICATION = 3;
int DIVISION = 4;
int EXIT = 5;
Scanner keyboard = new Scanner(System.in);
int choice;
do
{
System.out.println("Choose from the following:");
System.out.println("1. Add 2 integers");
System.out.println("2. Subtract 2 integers");
System.out.println("3. Multiply 2 integers");
System.out.println("4. Divide 2 integers");
System.out.println("5. Exit");
System.out.print("Enter choice: ");
choice = keyboard.nextInt();
if ((choice == 1) || (choice == 2) || (choice == 3) || (choice == 4))
{
System.out.print("Enter first integer: ");
int left = keyboard.nextInt();
System.out.print("Enter second integer: ");
int right = keyboard.nextInt();
switch (choice)
{
double Result;
case 1:
Result = left + right;
System.out.println(left + " + " + right + " = " + Result);
break;
case 2:
Result = left - right;
System.out.println(left + " - " + right + " = " + Result);
break;
case 3:
Result = left * right;
System.out.println(left + " * " + right + " = " + Result);
break;
case 4:
Result = left / right;
System.out.println(left + " / " + right + " = " + Result);
}
System.out.println();
}
} while (choice != 5);
}
}
errors:
BasicCalculator.java:34: error: case, default, or '}' expected
int Result;
^
BasicCalculator.java:34: error: case, default, or '}' expected
int Result;
^
BasicCalculator.java:34: error: case, default, or '}' expected
int Result;
the above code is my project for my intro to computer programming class,i've ran into a few errors that are stemming from formatting issues. can I get some basic help with whats causing the errors. I'm still trying to get used to reading the errors description in notepad++ and understanding what they mean.
You cannot declare a variable inside a switch statement outside of a case label. If you want Result to be shared among all cases, including the default, declare it prior to switch, like this:
double Result = 0;
switch (choice)
{
case 1:
Result = left + right;
System.out.println(left + " + " + right + " = " + Result);
break;
case 2:
Result = left - right;
System.out.println(left + " - " + right + " = " + Result);
break;
case 3:
Result = left * right;
System.out.println(left + " * " + right + " = " + Result);
break;
case 4:
Result = left / right;
System.out.println(left + " / " + right + " = " + Result);
}
(I'm not sure this is completely correct as I don't really do Java, but here goes)
I think the error is where you have double Result; inside the switch statement - Java only allows either case or default inside the switch statement. Try placing the double Result line just above your switch (... line. Also, I'd make sure that all of the lines below your case 1/2/3 statements are properly indented - it may just be the formatting on stack exchange, but the Result = ... lines look one character ahead (not sure if this would make a difference, but it's best to always have consistent code).

Simple Calculator Operation

I am attempting to simplify my long code of a calculator program, but I have a road block. I have a new else if statement for each calculator operator, but what I want to do is allow the user to manually type in, on one line, the entire operation they would like to perform and have the code compute it.
Here's what I have:
do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();
if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();
answer = num1 * num2;
System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);
answer = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");
This is what I want the output to be:
Enter operation:
4 * 6
4 * 6 = 24
Should be able to enter any operation here on one line. I am not asking you to write my calculator for me, I am asking how to allow the computer to read in the entire operation off one line and compute it, then print it.
If you use scanner readLine then you can read a whole line
e.g.
4 * 6
This line can then be split to get three tokens
String tokens [] = line.split (" ");
then you can see what operation to do based upon token[1]
if (token[1].equals ("-") {
//lets minus token[2] from token[0]
// need to convert String to Number
}
You can use String.split and store it in an array. Then it will return an array of string, parse those back to integers. the do the operation you want. The x variable will be the result.
if(maininput.contains("+")) {
String[] stringarr = string.split("\\+");
int x = Integer.parseInt(stringarr[0]) + Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " + " + stringarr[1] + " = " + x);
} else if(maininput.contains("-")) {
String[] stringarr = string.split("\\-");
int x = Integer.parseInt(stringarr[0]) - Integer.parseInt(stringarr[1]);
System.out.println(stringarr[0] + " - " + stringarr[1] + " = " x);
}
... And so on.
You could try parsing the line using a Pattern object, something like this:
Pattern opPattern = Pattern.compile("(\\d+) *([+-*/]) *(\\d+)");
Matcher matcher = opPattern.matcher(userLine);
if(matcher.find()) {
int op1 = Integer.toValue(matcher.group(1));
int op2 = Integer.toValue(matcher.group(3));
String op = matcher.group(2);
if(op.equals("+")) {
// do + op ...
} else ... {
// etc...
}
} else {
// error in line, not the form of an operation
}
Have a look at the javadoc, as I'm not sure if I used the correct method names and the like, just tried to illustrate the idea...

Categories