+ 4

What's wrong with my code?

I just got to switches on the java tutorial on sololearn and I tried to make a calculator using everything I learned but apparently I'm using switches wrong and I don't know what it is. I also want to know if theres a way I can make a calculator like this but with smaller lines of code. import java.util.Scanner; public class UpdatedCalculator { public static void main(String[] args) { double fnum,snum,answer; answer = 0; String operator; Scanner s = new Scanner(System.in); System.out.println("Enter First Number:\t"); fnum = s.nextDouble(); System.out.println("\nEnter Second Number:\t"); snum = s.nextDouble(); System.out.println("Choose your operator:"); System.out.println("\nAddition(a) \n\nSubtraction(b) \n\nDivision(c) \n\nMultiplication(d)"); operator = s.nextLine(); switch (answer) { case a: answer = fnum + snum; break; case b: answer = fnum - snum; break; case c: answer = fnum/snum; break; case d: answer = fnum * snum; break; default: System.out.println("No Such Operation."); } System.out.println(" "); if(operator.equals(a) || operator.equals(b) || operator.equals(c) || operator.equals(d)) { System.out.println("Answer: " + answer); }else { System.out.println("\n\nError! \n\nError! \n\nError!"); } } }

12th Nov 2017, 7:26 PM
Unidentified
Unidentified - avatar
3 Answers
+ 32
hey , see again the switch , by mistake u put answer in place of operator , when we use .equals // both sides must be string , ie u must enclose a, b, c in "" here is a improved version â˜ș👍 import java.util.Scanner; public class UpdatedCalculator { public static void main(String[] args) { double fnum,snum,answer; answer = 0; String operator; Scanner s = new Scanner(System.in); fnum = s.nextDouble(); snum = s.nextDouble(); operator = s.next(); if (operator.equals("a")) answer = fnum + snum; else if(operator.equals("b")) answer = fnum - snum; else if(operator.equals("c")) answer = fnum/snum; else if(operator.equals("d")) answer = fnum * snum; else{ System.out.println("No Such Operation."); System.exit(0); } System.out.println("\nAnswer "+answer); } }
12th Nov 2017, 7:46 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 6
You forgot the double quotes around your letters. It should be: case "a": // code instead of: case a: // code This is also present in your equals() method calls near the end of the program. Happy coding! :D
12th Nov 2017, 7:33 PM
LunarCoffee
LunarCoffee - avatar
+ 3
Thank you for the help!, and thanks for the improved version!!
12th Nov 2017, 8:15 PM
Unidentified
Unidentified - avatar