2014-02-26 65 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