如何将其转换为switch语句

时间:2018-12-08 05:56:20

标签: java switch-statement

if(x > -1 && x <1)  
  System.out.println("x is between -1 to 1");  
else if (x==5)  
  System.out.println("x is 5");  

else  
  System.out.println("x is some other values");  

3 个答案:

答案 0 :(得分:1)

仅当变量采用的值是确定的而不是值的范围时,才可以使用switch语句。假设您可以将输入仅作为整数。 所以你可以这样:

switch(x):

{

case 5:

System.out.println("x is 5");

break;


case -1:

System.out.println("x is -1");

break;

case 1:

System.out.println("x is 1");

break;

default:

System.out.println("x is some other value");

break;

}

答案 1 :(得分:1)

您甚至可以通过以下技巧在此处使用带有浮点或双精度值的切换

public static void main(String[] args)
{
    double value = 5.234;
    int absValue;

    if((int) Math.abs(value / 1) == 5 )
    {
        absValue = value == 5 ? 5 : 20; // if value is not exactly 5 then absValue should set to any value which is not 5 and not between -1 and 1
    }
    else
    {
        absValue = (int) Math.abs(value / 1) ;
    }

    switch (absValue)
    {
        case 0:
            System.out.println("x is between -1 and 1");
            break;

        case 5:
            System.out.println("x is 5");
            break;

        default:
            System.out.println("x is some other value");
    }
}

答案 2 :(得分:0)

假设xint,则介于-11之间的唯一方法是使用0,因此只有三个switch语句中的情况:

switch (x) {
    case 0:
    System.out.println("x is between -1 and 1");
    break;

    case 5:
    System.out.println("x is 5");  
    break;

    default:
    System.out.println("x is some other value");
}