What's wrong with my code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What's wrong with my code?

It keeps saying that it can recognize symbol in the scanner (System.in) area. Please help. I'm trying to make a calculator in Java. import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner num = newScanner(System.in); int n = num.nextInt(); String op = num.nextLine(); int n2 = num.nextInt(); if (op == "+") { System.out.println(n + n2); } if (op == "-") { System.out.println(n - n2); } if (op == "x") { System.out.println(n * n2); } if (op == "/") { System.out.println(n / n2); } } }

22nd Apr 2021, 3:38 PM
Ava
Ava - avatar
12 Answers
+ 3
import java.util.*; public class Program { public static void main(String[] args) { Scanner num = new Scanner(System.in); int n = num.nextInt(); char op =num.next(). charAt(0); int n2 = num.nextInt(); if(op=='+') { System.out.println(n + n2); } if(op=='-') { System.out.println(n - n2); } if(op =='*') { System.out.println(n * n2); } if(op == '/') { System.out.println(n / n2); } } } //Check out the syntax once again, I have modified a bit.
22nd Apr 2021, 4:11 PM
Aditya
Aditya - avatar
+ 2
In case you're wondering what num.next().charAt(0) does, you can have a look at my answer in this thread - https://www.sololearn.com/discuss/2736943/?ref=app
22nd Apr 2021, 4:22 PM
Soumik
Soumik - avatar
+ 2
You're welcome, Ava🙂. Btw, you can also ping someone using the @ symbol like this Ava, so they will get a notification you did so.
24th Apr 2021, 2:17 AM
Soumik
Soumik - avatar
+ 1
Scanner num = new Scanner(System.in)
23rd Apr 2021, 2:56 PM
Java Developer
Java Developer - avatar
+ 1
Use char instead of string in declaring the variable op. If you use string, the n is correctly read as an integer and the remaining part that is op and n2 are togetherly read as a string. Just modify your program and you will achieve correct output. Good luck👍
23rd Apr 2021, 7:00 PM
Muhammed Shafi
Muhammed Shafi - avatar
+ 1
Aditiya, thank you. This greatly helped me. It will be great for me to get to study the syntax
23rd Apr 2021, 8:02 PM
Ava
Ava - avatar
+ 1
Thank you so much for explaining, Soumik
23rd Apr 2021, 8:03 PM
Ava
Ava - avatar
+ 1
Soumik thanks
24th Apr 2021, 2:18 AM
Ava
Ava - avatar
0
Go
23rd Apr 2021, 4:29 PM
Irangi Fernando
Irangi Fernando - avatar
0
Leave a space between new keyword and scanner.... And take op input as a character.... Or else use op.equals() instead of ==
24th Apr 2021, 5:44 AM
Aditya Raj Singh
Aditya Raj Singh - avatar
0
Mm
24th Apr 2021, 10:45 AM
Islombek Turg'unov
Islombek Turg'unov - avatar
0
Use * instead of x
24th Apr 2021, 10:53 AM
Soumyajoy Das
Soumyajoy Das - avatar