I am trying to generate a digit to execute switch statement but it is not generating proper result. But when the IF block is removed it works properly. What is the problem in the code?
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 );
}
}
}
The trick is that the isDigit method is meant for characters and detecting whether they represent a number. For example
isDigit(8) == falsebecause 8 maps to backspace in ASCII, butisDigit('8') == truesince ‘8’ is really 56 in ASCII.What you might want to do is remove the if altogether and change your random generation to always produce a number between 1 and 4. This can be done as follows:
The
% 4will make sure the value is always between 0 and 3, and the+ 1shifts the range to 1 to 4.You can also use the Random class included with java:
Once again the
+ 1shifts the range to be 1 to 4 inclusive.