Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch Statement help in Java

Ok I know i asked before but i got a little further than what i had. So here is my problem.

I have to write a program that will read in two numbers from the user (double type). The program should then display a menu of options to the user allowing them to add, multiply or divide the first number by the second. My program should catch division by zero and report the error to the user.

Here is what i have so far I am just kind of lost on where to put the Math part in the switch statments

import java.util.*;
public class tester
{
public static void main(String[] args) 
    {
    Scanner console = new Scanner(System.in);
    double MyDouble1;
    double MyDouble2;

    System.out.print(" Please enter the first decimal number: ");
    MyDouble1 = console.nextDouble();

    System.out.print(" Please enter the second decimal number: ");
    MyDouble2 = console.nextDouble();

    // Display menu graphics
    System.out.println("============================");
    System.out.println("|   MENU SELECTION DEMO    |");
    System.out.println("============================");
    System.out.println("| Options:                 |");
    System.out.println("|        1. Addition       |");
    System.out.println("|        2. Multiply       |");
    System.out.println("|        3. Divide         |");
    System.out.println("|        4. Exit           |");
    System.out.println("============================");

    MyDouble1 = console.nextDouble();

    System.out.print(" Select option: ");
    // Switch construct
    switch (MyDouble1)
    {
    case 1:
      System.out.println("Addition selected");   

      break;
    case 2:
      System.out.println("Multiply selected");  
      break;
    case 3:
      System.out.println("Divide selected");  
      break;
    case 4:
      System.out.println("Exit selected");
      break;
    default:
      System.out.println("Invalid selection");
      break; 
    }

    }
}

Ive looked for other tuts but i dont know if i was looking in the right place. Any help would be nice and thank you.

like image 339
user3348515 Avatar asked Nov 01 '22 04:11

user3348515


1 Answers

Put code inside case, you also need a variable choice for operation.

switch (choice) //choice has to be int, byte, short, or char (String with java 7)
{
    case 1:
        // Your code goes here
        System.out.println("Addition selected");
        break;
    case 2:
        System.out.println("Multiply selected");
        break;
    case 3:
        System.out.println("Divide selected");
        break;
    case 4:
        System.out.println("Exit selected");
        break;
    default:
        System.out.println("Invalid selection");
        break;
}
like image 135
fastcodejava Avatar answered Nov 15 '22 04:11

fastcodejava