How to Correctly Accept Arithmetic Operators as User Input

Viewed 7

Problem : My program is not recognizing my arithmetric operator input

I run into problems when the program tries to identify my arithmetic operator. I've tried to use quotes i.e( "+", "-", etc.) and no qoutes i.e (+, -,, etc.) but I still can't get the program to complete an equation. What should I do to fix this problem?

Output

****Choose 1 number between 200 and 1000...

800

Choose another number between 200 and 1000...

800

Choose an operator (+ , - , * or /)

"+"

is not a valid operator

Invalid Entry****


Full Program

//This program takes to double values and an arithmetic operator from the user and does a basic arithmetic equation
//based on user input using conditional statements and scanners

 import java.util.Scanner;

 public class Assignment_2{

 public static void main(String[] args){

// intialize scanners
Scanner DoubleScan = new Scanner (System.in);
Scanner OpScan = new Scanner (System.in);

// prompt user for first number
System.out.println("Choose 1 number between 200 and 1000...");

// accept first user input as double
Double doublein1 = DoubleScan.nextDouble();

//store first user input as string
String doublein1str = Double.toString(doublein1);

//prompt user for second number 
System.out.println("Choose another number between 200 and 1000...");

//accept second user input at double
Double doublein2 = DoubleScan.nextDouble();

//store second user input as string
String doublein2str = Double.toString(doublein2);

//prompt user for arithmetic operator choice
System.out.println("Choose an operator (+ , - , * or /)");

//accept user arithmetic operator choice
String Op = OpScan.next();

//if numbers entered are not between 200 and 100 create error message
if (!(200 < doublein1 && doublein2 <= 1000)){
    
    System.err.println(doublein1 + " or " + doublein2 + " is not a valid number");

}

//if operators are not +, -, *, or / create an error message
if (!(Op == "+"|| Op == "-" || Op == "*" || Op == "/")){
    
    System.err.println(Op + " is not a valid operator");
}

//depending on which operator is chosen calcutate accordingly with numbers 1 and 2 
if(Op == "+"){
    System.out.println("Evaluation: " + doublein1str + " + " + doublein2str + " = " + (doublein1 + doublein2));

} else if (Op == "-"){
    System.out.println("Evaluation: " + doublein1str + " - " + doublein2str + " = " + (doublein1 - doublein2)); 

} else if (Op == "*"){
    System.out.println("Evaluation: " + doublein1str + " * " + doublein2str + " = " + (doublein1 * doublein2));

} else if (Op == "/"){
    System.out.println("Evaluation: " + doublein1str + " / " + doublein2str + " = " + (doublein1 / doublein2));

    // if operator does not match any above inform user of invalid entry
} else;{
    System.out.println("Invalid Entry");
}

 // close scanners   
DoubleScan.close();
OpScan.close();


//end
}
[I think something is wrong in this section of the code][1]}
0 Answers
Related