java代码有什么问题?

时间:2012-04-21 11:08:04

标签: java if-statement enums

我正在尝试生成一个数字来执行switch语句,但它没有生成正确的结果。但是当IF块被移除时,它可以正常工作。代码中有什么问题?

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 );
                  }
        }

}

3 个答案:

答案 0 :(得分:3)

您没有正确使用isDigit(),它将char作为参数,而不是int,请参阅此链接:http://www.tutorialspoint.com/java/character_isdigit.htm

答案 1 :(得分:2)

诀窍是isDigit方法适用于字符并检测它们是否代表数字。例如isDigit(8) == false因为8在ASCII中映射到退格,但是isDigit('8') == true因为'8'在ASCII中实际上是56。

您可能想要做的是完全删除if并将随机生成更改为始终生成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(包括1和4)。

答案 2 :(得分:1)

isDigit()实质上测试48-57范围内的ascii值,即数字字符。机会是,这不是Clothes

http://www.asciitable.com/