1

The "switch case" witch I have write for sin,cos,tan,cot doesn't work when I enter them in operator and it goes to entering second number. Where is my fault? Here is my code:

import java.util.Scanner;

public class MainClass {

    public static void main(String args[]){
        Scanner NumInput = new Scanner(System.in);
        double firstNum = 0;
        double secondNum = 0;
        double result = 0;
        System.out.println("Enter first number: ");
        firstNum = NumInput.nextDouble() ;
        System.out.println("Enter operator: ");
        String amalgar = NumInput.next();
            if (amalgar == "sin" || amalgar == "cos" || amalgar == "tan" || amalgar == "cot"){
            switch(amalgar){
        case "sin":
            result = Math.toRadians(Math.sin(firstNum));
            break;
        case "cos":
            result = Math.toRadians(Math.cos(firstNum));
            break;
        case "tan":
            result = Math.toRadians(Math.tan(firstNum));
            break;
        case "cot":
            result = (Math.toRadians(Math.cos(firstNum))/Math.toRadians(Math.sin(firstNum)));
            break;

        default : 
            break;



            }
            System.out.println(Math.toRadians(result));
            }
            else

                System.out.println("Enter second number: ");
                secondNum = NumInput.nextDouble();  
            switch (amalgar){
        case "+":
            result = firstNum + secondNum;
            break;
        case "-":
            result = firstNum - secondNum;
            break;
        case "*":
            result = firstNum * secondNum;
            break;
        case "/":
            result = firstNum / secondNum;
            break;

        default:
            System.out.println("nemifahmam chi neveeshti");
        }

            System.out.println(result);

    }
}
SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
Decimal
  • 11
  • 1
  • 1
  • 3

1 Answers1

1

The problem lies with this if condition:

if (amalgar == "sin" || amalgar == "cos" || amalgar == "tan" || amalgar == "cot"){

Using == only evaluates to true if you have the same object (i.e. two identical references) but "sin"(or "cos",etc) and amalgar are always two different objects. You should use equals() instead to compare the value. (see How do I compare strings in Java?)

Better yet, don't use the if-else block at all. Use switch, because if you don't match one of those four you won't evaluate anything but your default case, which is empty.

Community
  • 1
  • 1
Linus
  • 894
  • 7
  • 13