mardi 6 juillet 2021

Condition in Java but always skip the rest of if and if else [duplicate]

  1. This is basic calculator.

  2. I love programming

  3. All of if and if else will be skipped downward, If I select + operator, it doesn't follow the if + statement.

    Scanner Input = new Scanner(System.in);
    
    try {
        System.out.print("Enter a number: ");
        int num1 = Input.nextInt();
    
        System.out.print("Enter an operator: ");
        String operator = Input.nextLine();
        Input.nextLine();
        String FinalOp = operator;
    
        System.out.print("Enter a second number: ");
        int num2 = Input.nextInt();
        // this part of decision, it doesn't work.
        if ("+".equals(FinalOp)) {
            System.out.println("Your result is " + (num1 + num2));
        } else if ("-".equals(FinalOp)) {
            System.out.println("Your result is " + (num1 - num2));
        } else if ("x".equals(FinalOp)) {
            System.out.println("Your result is " + (num1 * num2));
        } else if (":".equals(FinalOp)) {
            System.out.println("Your result is " + (num1 / num2));
        } else {
            System.out.println("Your answer is not valid");
        }
    }
    catch(InputMismatchException e) {
        System.out.println("similar to try and except in Python");
    }
    

Aucun commentaire:

Enregistrer un commentaire