2012-04-21 26 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(含)。