2012-04-21 27 views
1

我想要生成一個數字來執行switch語句,但它不會生成正確的結果。但是當IF塊被移除時,它可以正常工作。代碼中有什麼問題?Java代碼有什麼問題?

import static java.lang.Character.isDigit; 
public class TrySwitch 
{ 
    enum WashChoise {Cotton, Wool, Linen, Synthetic } 
    public static void main(String[]args) 
     { 

     WashChoise Wash = WashChoise.Cotton; 
     int Clothes = 1; 
     Clothes = (int) (128.0 * Math.random()); 
     if(isDigit(Clothes)) 
     { 
      switch (Clothes) 
      { 
       case 1: 
       System.out.println("Washing Shirt"); 
       Wash = WashChoise.Cotton; 
       break; 
       case 2: 
       System.out.println("Washing Sweaters"); 
       Wash = WashChoise.Wool; 
       break; 
       case 3: 
       System.out.println("Socks "); 
       Wash = WashChoise.Linen; 
       break; 
       case 4: 
       System.out.println("washing Paints"); 
       Wash = WashChoise.Synthetic; 
       break; 

      } 
       switch(Wash) 
       { 
        case Wool: 
        System.out.println("Temprature is 120' C "+Clothes); 
        break; 
        case Cotton: 
        System.out.println("Temprature is 170' C "+Clothes); 
        break; 
        case Synthetic: 
        System.out.println("Temprature is 130' C "+Clothes); 
        break; 
        case Linen: 
        System.out.println("Temprature is 180' C "+Clothes); 
        break; 

       }    
       } 
     else{ 
      System.out.println("Upps! we don't have a digit, we have :"+Clothes); 
        } 
     } 

} 
+1

「不正常工作」是什麼意思? – luketorjussen 2012-04-21 11:12:47

回答

2

訣竅在於,該方法ISDIGIT是爲字符,並檢測它們是否代表一個數字。例如isDigit(8) == false,因爲8映射到ASCII中的退格,但isDigit('8') == true自'8'確實是56的ASCII。

你可能想要做的是,如果完全刪除和更改隨機生成總是產生1到4之間的數字。這是可以做到如下:

Clothes = ((int) (128.0 * Math.random())) % 4 + 1; 

% 4將確保值始終爲0和3之間,並且+ 1轉移至1〜4

也可以使用包含用java Random類:

import java.util.Random; 
... 
Clothes = new Random().nextInt(4) + 1 

再次,+ 1將範圍轉換爲1到4(含)。