java - 奇怪的 if 语句给我带来了问题

标签 java

我要解决的问题是

An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.

IPv4 addresses are represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255 inclusive, separated by dots, e.g., 172.16.254.1.

Given a string, find out if it satisfies the IPv4 address naming rules.

Example

For inputString = "172.16.254.1", the output should be isIPv4Address(inputString) = true;

For inputString = "172.316.254.1", the output should be isIPv4Address(inputString) = false.

316 is not in range [0, 255].

For inputString = ".254.255.0", the output should be isIPv4Address(inputString) = false.

There is no first number.

Input/Output

[execution time limit] 3 seconds (java)

[input] string inputString

Guaranteed constraints: 1 ≤ inputString.length ≤ 30.

[output] boolean

true if inputString satisfies the IPv4 address naming rules, false otherwise.

我真的很接近解决这个问题,但我似乎无法克服这样一个奇怪的逻辑错误,java似乎无法识别它。基本上我正在使用 Integer.parseInt(temp) 解析字符串并检查它是否小于或等于 255。在不应该返回 false 的情况下,temp = 172。我知道这一点是因为我'我已经调试了我的代码好几次了。 代码:

while(inputString.length() > 0){
    if(inputString.lastIndexOf('.') == -1) {
        temp = inputString.substring(0, inputString.length());
        if(Integer.parseInt(temp) <= 255)
            {return false;}
        for(int i = 0; i<temp.length(); i++) {
            if(!Character.isDigit(temp.charAt(i))){
                return false;
            }else {
                return true;
            }
        }
    }

while 循环有点长,因为它处理 IPV4 地址的其他部分,但我只插入这个,因为我认为它对于解决我的问题更重要。如果需要,我可以放置整个代码。

最佳答案

这里有两个大问题:

  1. 为什么返回falseInteger.parseInt(temp) <= 255 ?不是 false返回表示错误? IP 号 <= 255 完全不是错误!
  2. 您的for循环,显然您打算检查所有数字的有效性,但仅检查第一个数字。为什么?您的 if 的两种情况循环内返回。摆脱else return true;案例if 。尽管您确实想要返回 false如果您发现一个坏数字,您还希望立即保持循环,只要您找到好数字。

关于java - 奇怪的 if 语句给我带来了问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50013277/

相关文章:

java - Spring 安全 3.1

java - 如何从 Spring @Query 注解调用 SQL 函数

java - 验证 Mockito 中同一方法的后续调用的参数

java - 关于java方法递归返回的问题

java - 匹配器断言两个对象

java - 为什么接口(interface)变量是public

java - 使用 Transformer 缩进 XML 文本

java - Ionic - 'platform add android' 命令失败,退出代码为 ENOENT

java - 如何更改一个数组中另一个数组的值?

java - 生成固定长度的随机数组