Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java switch always runs the default code

I'm a beginner at java and I've been working on this as a little perfect. It's supposed to be a simple calculator. I know there are probably better/more efficient ways to do this, but this is not what I'm looking for. I ran into a small issue when using a switch to choose what operation will be run. Basically, what happens is that every time I run the code it chooses the right code to run (if the String entered is "+", it will add the doubles), how ever it always seems to afterwards run the default code (which prints "Command not recognized."). If I remove the default code it works perfectly (of course, that way, if the user enters an unknown command it will give an error) and I could easily do that, but what I really want is a way to have a default code and to know why it isn't working this way. Please, Help. Thanks.

import java.util.Scanner;
public class App {
public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    double v1 = scan.nextDouble();
    double v2;
    double v3;
    scan.nextLine();
    while(1<2){
    String op = scan.nextLine();
    switch(op){
    case "+":
        v2 = scan.nextDouble();
        v1 = v2 + v1;
        System.out.println("="+v1);
        break;
    case "-":
        v2 = scan.nextDouble();
        v1 = v2 - v1;
        System.out.println("="+v1);
        break;
    case "*":
        v2 = scan.nextDouble();
        v1 = v2 * v1;
        System.out.println("="+v1);
        break;
    case "/":
        v2 = scan.nextDouble();
        v1 = v1 / v2;
        System.out.println("="+v1);
        break;
    case "^":
        v2 = scan.nextDouble();
        v3 = v1;
        for(int i = 1;i<v2;i++){
            v1 = v1*v3;
        }
        System.out.println("="+v1);
        break;
    case "%":
        v2 = scan.nextDouble();
        v1 = (v1/100)*v2;
        System.out.println("="+v1);
        break; 
    default:
        System.out.println("Command not recognized.");
            }
        }
    } 
}

The Output is something like this:

5
*
5
=25.0
Command not recognized.
like image 569
Diego Perozo Avatar asked Sep 28 '22 07:09

Diego Perozo


1 Answers

You should use scan.next() instead of scan.nextLine() in this line:

String op = scan.next();

When you do scan.nextLine() it consumes the new line character, so op gets set to "new line" and the switch ends in the default behavior.

Using scan.next() you will be able to do this:

5
*
5
=25.0
*
2
=50.0
/
25
=2.0
like image 100
Anderson Vieira Avatar answered Oct 03 '22 06:10

Anderson Vieira