首页 > 解决方案 > 为什么我的程序只对其中一个 if 语句执行 else 语句

问题描述

我希望我的代码确保所有 if 语句都能正常工作,如果其中一个不起作用,它应该指出那个特定的语句不正确并且不显示 IP 地址部分。现在当我这样做时,它只适用于第四个。其他人说它不正确但仍然输入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);
    }
}

标签: java

解决方案


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

推荐阅读