1

I want to switch-case using the condition which is of type String given by user input. But it's not working. It goes to default statement automatically. Please can someone confirm the issue? Below is the code :

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    
    Scanner sc = new Scanner(System.in);
    
    
    System.out.println("Please input number a: ");
      int a = sc.nextInt();
      
    System.out.println("Please input number b: "); 
      int b= sc.nextInt();

      System.out.println("Please enter the operation: ");
        String operation =sc.nextLine();
    
    switch(operation) {
      
    case "Addition" : System.out.println("Addtion of a & b = "+(a+b) );
    break;
    
    case "Subtraction": System.out.println("Subtraction of a & b = "+(a-b) );
    break;
    
    case "Multiply" : System.out.println("Subtraction of a & b = "+(a*b) );
    break;
    
    case "Divide": System.out.println("Subtraction of a & b = "+(a/b) );
    break;
    
    case "Modulo" : System.out.println("Subtraction of a & b = "+(a%b) );
    break;
    
    default : System.out.println("Exit");
    }
}

}

  • 2
    Read the dangling new line left over from `int a = sc.nextInt();` before trying to use `sc.nextLine();` to get more input – MadProgrammer May 16 '22 at 03:21

0 Answers0