+ 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); } } }
12 Respostas
+ 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.
+ 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
+ 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.
+ 1
Scanner num = new Scanner(System.in)
+ 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👍
+ 1
Aditiya, thank you. This greatly helped me. It will be great for me to get to study the syntax
+ 1
Thank you so much for explaining, Soumik
+ 1
Soumik thanks
0
Go
0
Leave a space between new keyword and scanner....
And take op input as a character....
Or else use op.equals() instead of ==
0
Mm
0
Use * instead of x