为什么我的程序只对if语句之一执行else语句

时间:2020-10-18 20:43:49

标签: java

我希望我的代码确保所有的if语句都起作用,并且如果其中之一不起作用,则应指出该特定语句不正确,并且不显示IP地址部分。现在,当我这样做时,它仅适用于第4个。其他人说这是不正确的,但仍然放置了IP地址。

{
    Scanner scan = new Scanner(System.in);

    System.out.println("Please enter the first octet:");
    int a = scan.nextInt();
    System.out.println("Please enter the second octet:");
    int b = scan.nextInt();
    System.out.println("Please enter the third octet:");
    int c = scan.nextInt();
    System.out.println("Please enter the fourth octet:");
    int d = scan.nextInt();

    if (!(a >= 0 && a <= 255))
    {
        System.out.println("Octet 1 is incorrect");
    }
    if (!(b >= 0 && b <= 255))
    {
        System.out.println("Octet 2 is incorrect");
    }
    if (!(c >= 0 && c <= 255))
    {
        System.out.println("Octet 3 is incorrect");
    }
    if (!(d >= 0 && d <= 255))
    {
        System.out.println("Octet 4 is incorrect");
    }

    else
    {
        System.out.println("IP Address:" + a + "." + b + "." + c + "." + d);
    }
}

1 个答案:

答案 0 :(得分:2)

else语句始终只能属于一个if条件。

我假设您要验证所有ip地址八位字节,并在其中一个不在有效范围内时显示一条消息。仅在地址有效的情况下才应打印(您当前的else指令)。

我建议在运行检查之前创建一个布尔变量。这个布尔值将告诉您四个字节是否正确。

boolean allOctetsValid = true;
if (!(a >= 0 && a <= 255))
{
    System.out.println("Octet 1 is incorrect");
    allOctetsValid = false;
}
if (!(b >= 0 && b <= 255))
{
    System.out.println("Octet 2 is incorrect");
    allOctetsValid = false;
}
if (!(c >= 0 && c <= 255))
{
    System.out.println("Octet 3 is incorrect");
    allOctetsValid = false;
}
if (!(d >= 0 && d <= 255))
{
    System.out.println("Octet 4 is incorrect");
    allOctetsValid = false;
}

if(allOctetsValid)
{
    System.out.println("IP Address:" + a + "." + b + "." + c + "." + d);
}

这只是一种可能的解决方案。

其他改进:

可以简化实际条件!(d >= 0 && d <= 255),也可以写为0 <= d && d <= 255

考虑创建一个方法来返回一个八位位组是否有效,即重复条件四次。示例:

private boolean isValidOctet(int octet)
{
    return 0 <= octet && octet <= 255;
}