java - 为什么我的程序只对其中一个 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);
}
}
解决方案
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;
}
推荐阅读
- c - 由 8 个 __m256i 寄存器表示的矩阵的 AVX2 转置
- python - 在特定模式之前和之后获取完整的字符串
- elasticsearch - 如何通过不匹配模式的 kv 过滤器排除解析事件
- python - 在 python pandas 中存款的储蓄计划的累积回报
- python - Python 3.7 上的 NameError/列表分配索引错误
- javascript - 使用 axios 对拦截器进行单元测试会引发错误
- gnuplot - 如何填充定义范围内两条曲线之间的部分?
- docker - 无法在 docker 容器内找到视图
- python - 如何使函数“addlevels”在我的主代码中工作?
- java - 使用 apache commons csv 按索引大小而不是 withFirstRecordAsHeader 读取 csv