2013-09-27 161 views
1

我無法將此程序從if-else-if語句轉換爲switch語句。任何幫助,將不勝感激。在java中將if-else-if語句轉換爲switch語句

import java.util.Scanner; 

public class ifToSwitchConversion { 


    public static void main(String [] args) { 

     // Declare a Scanner and a choice variable 
     Scanner stdin = new Scanner(System.in); 
     int choice = 0; 

     System.out.println("Please enter your choice (1-4): "); 
     choice = stdin.nextInt(); 

     if(choice == 1) 
     { 
      System.out.println("You selected 1."); 
     } 
     else if(choice == 2 || choice == 3) 
     { 
      System.out.println("You selected 2 or 3."); 
     } 
     else if(choice == 4) 
     { 
      System.out.println("You selected 4."); 
     } 
     else 
     { 
      System.out.println("Please enter a choice between 1-4."); 
     } 

    } 


} 
+2

來吧,你甚至懶得去查看switch語句是如何工作的嗎? –

+1

是的,我要回應Hatori。這是一個簡單的問題(這可能是爲什麼有這麼多快速答案),但通常在StackOverflow上需要顯示第一次嘗試,並在遇到特定問題時發佈。 –

+0

是的,我對我毫不費力的提問感到非常抱歉。只是這個分配是在一個小時內完成的,我不得不去某個地方,所以我擔心我沒有時間去閱讀它並編寫一個程序。再一次,抱歉它不會再發生。 – zaynv

回答

4
import java.util.Scanner; 

public class ifToSwitchConversion { 

public static void main(String [] args) { 

    // Declare a Scanner and a choice variable 
    Scanner stdin = new Scanner(System.in); 
    int choice = 0; 

    System.out.println("Please enter your choice (1-4): "); 
    choice = stdin.nextInt(); 


    switch(choice) { 
     case 1: 
      System.out.println("You selected 1."); 
      break; 
     case 2: 
     case 3: 
      System.out.println("You selected 2 or 3."); 
      break; 
     case 4: 
      System.out.println("You selected 4."); 
      break; 
     default: 
      System.out.println("Please enter a choice between 1-4."); 
    } 

    } 

} 
2
switch(choice) 
{ 
    case 1: 
     System.out.println("You selected 1."); 
     break; 
    case 2: 
    case 3: 
     System.out.println("You selected 2 or 3."); 
     break; 
    case 4: 
     System.out.println("You selected 4."); 
     break; 
    default: 
     System.out.println("Please enter a choice between 1-4."); 
} 
3

你可能想喜歡的事:

switch (choice) { 
    case 1: 
     System.out.println("You selected 1."); 
     break; 
    case 2: 
    case 3: // fall through 
     System.out.println("You selected 2 or 3."); 
     break; 
    case 4: 
     System.out.println("You selected 4."); 
     break; 
    default: 
     System.out.println("Please enter a choice between 1-4."); 
} 

我強烈建議你閱讀switch statement tutorial,這應解釋如何/爲什麼這個工程,因爲它確實。

+0

非常感謝,很抱歉沒有事先閱讀 – zaynv

+0

@Saad沒問題,很高興我能幫上忙。不要忘記[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)。 – arshajii

+1

對,剛纔我剛剛對此有所瞭解,因爲你可以看到 – zaynv