2014-02-05 181 views
0

這裏是我的if-else語句:如何將此if-else語句放入switch語句中?

public static void main(String[] args) { 

     Scanner input = new Scanner (System.in); 
     int number; 
     System.out.println("Enter Integer: "); 
     number = input.nextInt(); 
     if (number % 7 == 0) { 
       System.out.println(number + " is divisible by 7"); 
     } 
      else { 
       System.out.println(number + " isn't divisible by 7"); 
     } 
    } 
+5

[switch語句](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)。 – Maroun

+1

你需要轉換什麼?你要麼有無可否認的性格 – A4L

+2

聞起來就像做家庭作業一樣。爲什麼有人會寫這樣的代碼,然後想把它變成switch語句。 – neildo

回答

3
number = input.nextInt(); 
switch(number % 7) 
{ 
case 0: 
    System.out.println(number + " is divisible by 7"); 
    break; 

default: 
    System.out.println(number + " isn't divisible by 7"); 
} 
0
number = input.nextInt(); 
    a = number % 7 

switch (a) { 
      case 0: System.out.println(number + " is divisible by 7"); 
        break; 

      default: System.out.println(number + " isn't divisible by 7"); 
        break; 
     } 
0

檢查了這一點:

switch (number % 7) { 
    case 0: 
     System.out.println(number + " is divisible by 7"); 
     break; 
    default: 
     System.out.println(number + " isn't divisible by 7"); 
    } 

OR

switch (number % 7) { 
case 0: 
    System.out.println(number + " is divisible by 7"); 
    break; 
case 1: // Fall through 
case 2: 
case 3: 
case 4: 
case 5: 
case 6: 
    System.out.println(number + " isn't divisible by 7"); 
} 
6

沒關係開關 - 你不也不需要。
你可以把它變成一個聲明

System.out.println(number + " is" + (number % 7 == 0 ? "" : "n't") + " divisible by 7"); 
+0

不錯的一個....:D – Maroun

0

嘗試這樣;

Scanner input = new Scanner (System.in); 
int number; 
System.out.println("Enter Integer: "); 
number = input.nextInt(); 
int tempNumber = number % 7; 
switch(tempNumber) { 
     case 0: 
     System.out.println(number + " is divisible by 7"); 
     break; 
     default : 
     System.out.println(number + " isn't divisible by 7"); 
}