What's wrong with my code? | Sololearn: Learn to code for FREE!

+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); } } }

4/22/2021 3:38:52 PM

Ava

14 Answers

New Answer

+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.

+5

Put a space after new and then write Scanner(System.in) Ex Scanner Sc=new Scanner (System .in);

+1

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

+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

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

Soumik thanks

0

Ava, assuming that you are entering something like... 2 + 2 int n = num.nextInt(); reads the number 2 into n. String op = num.nextLine(); will then read " + 2" into op so it will not match any of your conditions.

0

0

Leave a space between new keyword and scanner.... And take op input as a character.... Or else use op.equals() instead of ==

0

0

Use * instead of x