-2

I want to ask user to insert operator and get the answer till user enters keys other than +,-,* or \ .I did the program like this.But it will not work properly.Its looping even for other keys.What is the problem with the coding?

public static void main(String Args[]) throws IOException
{

    InputStreamReader myrdr=new InputStreamReader(System.in);
    BufferedReader myBfr=new BufferedReader(myrdr);
    Scanner myScanner=new Scanner(System.in);

    String mathOp;
    float Res,Num1,Num2;


    System.out.print("Mathematical Operator :");
    mathOp=myBfr.readLine();




    Res=0;
    while(mathOp!="+"||mathOp!="-"||mathOp!="*"||mathOp!="\\")
    {
        System.out.print("Enter number one: ");
        Num1=myScanner.nextInt();

        System.out.print("Enter Number Two: ");
        Num2=myScanner.nextInt();

        switch(mathOp)
        {
            case "+":
                Res=Num1+Num2;
                break;

            case "-":
                Res=Num1-Num2;
                break;
            case "\\":
                Res=Num1/Num2;
                break;
            case "*":
                Res=Num1*Num2;
                break;

            default:
            {
                System.out.println("Programme Exits");
                return;
            }
        }

        System.out.println("Answer is : "+Res);
        System.out.print("Mathematical Operator :");
        mathOp=myBfr.readLine();

    }



}

4 Answers4

1

Don't use == (which compares if the 2 operands are the same String object, which they aren't), use equals() (which compares if the contents of the 2 String objects are the same).

But better yet, simplify your code to this:

while (!"+-*\\".contains(mathOp))

btw, divide is usually a normal slash /, not a backslash \.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    If `mathOp` is `+`, the result of `"+-*\\".indexOf("+")` will be `0`,because there is a `+` at the first index of the string `"+-*\\"`. And comparing this by `0 < 0` will result in jumping out of the loop. If `indexOf` can't find the `mathOp` in the string, it will return `-1` so it will go on looping. So, in the end... shouldn't the condition like `"+-*\\".indexOf(mathOp) > -1` or better `"+-*\\".contains(mathOp)`? – bobbel Feb 01 '14 at 13:11
  • @bobbel OP's code is testing for `!=`, so my logic was correct, however your suggestion of using `contains()` is a good one because it's easier to read, except I've changed it to `!contains()` to preserve the intention. – Bohemian Feb 01 '14 at 16:02
0

Make your while loop like this

while(mathOp.equals("+") || mathOp.equals("-") || 
mathOp.equals("//") || mathOp.equals("*"))

Use String.equals() to compare string in Java, not == or !=. To explain more, you shouldn't use == or != while comparing String values in Java because they check for equality for the values in the right and left operands. i.e a memory address in case of String objects ,which will not be equal for two different objects. You can make use of == and != with primitive datatypes and compile time constants. There is also a concept called String constant pool which has the compile time String constants created by using assignment operator like String new = "new"; without using new operator during object creation which can be compared using == or !=.

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
0

Yoy have to use someting like that

while((!mathOp.equals("+"))||(!mathOp.equals("-"))||(!mathOp.equals("*"))||(!mathOp.equals("\")))

0

First of all you should know the proper use of || and && True || False returns true True || False || False || False returns true,one True is enough to make the condition return true no matter how many false you have So in your case you are saying that if the input is different from one of them than let it proceed,so if you have + it will enter since + is different that -. You should instead use &&.

True && False returns False True && True && True && False returns False. One False is enough to return False no matter how many True you have. If you use && you would be telling the condition to return true only if all the sub-conditions are true,i.e it is different than + and different than - and different than * and different than .

Moreover, replace your "+" by '+' because the latter it is a character while the first is a string. == can be used only on characters,numbers and boolean values. To compare Strings you should use .equals("x")

Roudy Tarabay
  • 449
  • 1
  • 4
  • 18