0

Why the if statements are not working what is wrong with my code please help me to find out the bug(solved)

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); System.out.print("Enter next number: "); int num1 = sc.nextInt(); System.out.print("Enter operator: "); String operator=sc.next(); int sum = num + num1; int diff = num - num1; int mul = num * num1; int div = num / num1; if (operator=="+") { System.out.println("sum of numbers=" + sum); } else if (operator=="-") { System.out.println("The difference of numbers= " + diff); } else if (operator=="×") { System.out.println("the product= " + mul); } else if (operator=="Ă·") { System.out.println("the division= " + div); } else{ System.out.println("invalid operator"); } } }

9th Nov 2020, 5:48 AM
Rowdy Reddy
Rowdy Reddy - avatar
6 Answers
+ 4
U 'll need 1 more else stmt at last to satisfy syntax. May it be like: else { System.out.println("wrong operator"); }
9th Nov 2020, 5:50 AM
Alphin K Sajan
Alphin K Sajan - avatar
+ 1
If and else if statement is not work because condition is false in every operator. Variable operator store reference number of string And if you compare like Reference number == "+" Than its gives false . So try the equals method when you compare strings if(operator.equals("+"))
9th Nov 2020, 5:59 AM
Prathvi
Prathvi - avatar
0
I tried that but then also it's not working
9th Nov 2020, 5:56 AM
Rowdy Reddy
Rowdy Reddy - avatar
0
When I entered the operator it always giving output as invalid operator
9th Nov 2020, 5:57 AM
Rowdy Reddy
Rowdy Reddy - avatar
0
Thank you so much it's working now
9th Nov 2020, 6:00 AM
Rowdy Reddy
Rowdy Reddy - avatar
0
Welcome đŸ€—
9th Nov 2020, 6:02 AM
Prathvi
Prathvi - avatar