2014-02-26 136 views
5

好吧,我知道我以前问过,但我比我得到了一点点。所以这是我的问题。在Java中的开关语句帮助

我必须编写一个程序,用户可以读取两个数字(双精度型)。程序应该向用户显示一个选项菜单,允许他们添加,乘以或除以第二个数字。我的程序应该按零进行除法并将错误报告给用户。

这里是我到目前为止,我只是有种失去了在那里把数学部分的开关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; 
    } 

    } 
} 

伊夫寻找其他TUTS,但我不知道如果我一直在寻找的正确的位置。任何帮助将很好,谢谢。

+2

这是不是一个好主意'切换'双'。 – herohuyongtao

+0

您可能不应该重复使用'MyDouble1'来捕获用户想要执行的操作类型。 – Tyler

+1

不要用大写字母开头变量名...使用'camelCase'。 –

回答

2

将代码放在案例中,您还需要变量choice进行操作。

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

你说MyDouble1必须是int我可以吗? – user3348515