[英]What is wrong in java code?
我試圖生成一個數字來執行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 );
}
}
}
您沒有正確使用isDigit(),它使用char作為參數,而不是int,請參見以下鏈接: http ://www.tutorialspoint.com/java/character_isdigit.htm
訣竅是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)。
isDigit()本質上測試48-57范圍內的ascii值,即數字字符。 很有可能,這不是Clothes
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.