You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java程序中IP地址字符串输入异常问题求助

Fixing StringIndexOutOfBoundsException in Your IP Classification Program

What's Causing the Error?

Let's break down that error message first:

Error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 0 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3756) at java.base/java.lang.String.substring(String.java:1902) at cnPrac6.classFromDecimal(cnPrac6.java:7) at cnPrac6.main(cnPrac6.java:94)

The problem starts in your main method. When you use sc.nextInt() to read the user's choice (1 for Decimal, 2 for Binary), it only grabs the integer value—it leaves the newline character (\n) from the user pressing Enter stuck in the input buffer. The next sc.nextLine() call then reads this leftover newline as an empty string, so your str variable is completely empty when it gets passed to classFromDecimal.

In classFromDecimal, you call str.indexOf('.') on an empty string, which returns -1. Trying to run str.substring(0, -1) is invalid (since the end index can't be smaller than the start), hence the StringIndexOutOfBoundsException.

How to Fix It

Step 1: Clear the Input Buffer

Right after reading the choice with sc.nextInt(), add an extra sc.nextLine() to consume the leftover newline. This ensures your next sc.nextLine() actually reads the user's IP input, not an empty line:

int choice = sc.nextInt();
sc.nextLine(); // Add this line to clear the newline from the buffer

Step 2: Add Input Validation (Optional but Recommended)

To avoid similar issues down the line, add checks to ensure the user entered a valid IP string before processing it. For example:

  • Check if str is empty or blank
  • For decimal IPs, verify it has exactly 3 dots and valid numeric ranges
  • For binary IPs, check it's a valid 32-bit binary string (adjust based on your expected format)

Modified Full Code

Here's the corrected version of your program with the buffer fix, basic validation, and a small typo fix ("belings" → "belongs"):

import java.util.*;

public class cnPrac6 {
    static String classFromDecimal(String str) {
        // Validate decimal IP format first
        if (!str.contains(".") || str.isBlank()) {
            return "Invalid IP Format";
        }
        int index = str.indexOf('.');
        String ipsub = str.substring(0, index);
        int ip;
        try {
            ip = Integer.parseInt(ipsub);
        } catch (NumberFormatException e) {
            return "Invalid IP Value";
        }
        if (ip >= 1 && ip <= 126) return "A";
        else if (ip >= 128 && ip <= 191) return "B";
        else if (ip >= 192 && ip < 223) return "C";
        else if (ip >= 224 && ip <= 239) return "D";
        else return "E";
    }

    static String classFromBinary(String str) {
        // Basic validation for binary IP (adjust if you expect dotted binary format)
        if (str.isBlank() || str.length() != 32 && !str.contains(".")) {
            return "Invalid Binary IP Format";
        }
        if (str.charAt(0) == '0') return "A";
        else if (str.charAt(0) == '1' && str.charAt(1) == '0') return "B";
        else if (str.charAt(0) == '1' && str.charAt(1) == '1' && str.charAt(2) == '0') return "C";
        else if (str.charAt(0) == '1' && str.charAt(1) == '1' && str.charAt(2) == '1' && str.charAt(3) == '0') return "D";
        else if (str.charAt(0) == '1' && str.charAt(1) == '1' && str.charAt(2) == '1' && str.charAt(3) == '1' && str.charAt(4) == '1') return "E";
        else return "Error wrong address";
    }

    static void seprate(String str, String ipClass) {
        String network = "", host = "";
        // Skip processing if IP is invalid
        if (ipClass.startsWith("Invalid") || ipClass.equals("Error wrong address")) {
            System.out.println("Cannot separate Network/Host ID for invalid IP");
            return;
        }
        if (ipClass.equals("A")) {
            int index = str.indexOf('.');
            network = str.substring(0, index);
            host = str.substring(index + 1, str.length());
        } else if (ipClass.equals("B")) {
            int index = -1;
            int dot = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '.') {
                    dot += 1;
                    if (dot == 2) {
                        index = i;
                        break;
                    }
                }
            }
            if (index != -1) {
                network = str.substring(0, index);
                host = str.substring(index + 1, str.length());
            } else {
                System.out.println("Invalid IP format for Class B");
                return;
            }
        } else if (ipClass.equals("C")) {
            int index = -1;
            int dot = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '.') {
                    dot += 1;
                    if (dot == 3) {
                        index = i;
                        break;
                    }
                }
            }
            if (index != -1) {
                network = str.substring(0, index);
                host = str.substring(index + 1, str.length());
            } else {
                System.out.println("Invalid IP format for Class C");
                return;
            }
        } else if (ipClass.equals("D") || ipClass.equals("E")) {
            System.out.println("No network or host ID");
            return;
        }
        System.out.println("Network ID is " + network);
        System.out.println("Host ID is " + host);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String ipClassD = "";
        String ipClassB = "";
        System.out.print("In which category your address is: \n 1. Decimal \n 2. Binary \n");
        int choice = sc.nextInt();
        sc.nextLine(); // Fix: Clear leftover newline from input buffer
        System.out.print("Enter your address: ");
        String str = sc.nextLine();
        System.out.print("\n");
        switch (choice) {
            case 1:
                ipClassD = classFromDecimal(str);
                System.out.println("Given IP address belongs to Class " + ipClassD);
                seprate(str, ipClassD);
                break;
            case 2:
                ipClassB = classFromBinary(str);
                System.out.println("Given IP address belongs to Class " + ipClassB);
                seprate(str, ipClassB);
                break;
            default:
                System.out.println("Enter correct option");
        }
        sc.close(); // Clean up the scanner resource
    }
}

Key Notes

  • The main fix is the extra sc.nextLine() after sc.nextInt()—this ensures you capture the actual IP input instead of an empty string.
  • The added validation catches invalid inputs early, preventing unexpected exceptions later in the program.
  • I also closed the Scanner at the end to avoid resource leaks, a good practice for Java I/O.

内容的提问来源于stack exchange,提问作者KOUTILYA BHATT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:07:42