我已经编写了一个代码来从 ip 地址输入中查找子网掩码、广播 ID 等。但是,我收到以下错误,并且代码仅部分运行,没有语法错误:linux@ubuntu:~/Desktop$ javac Subnet.javalinux@ubuntu:~/Desktop$ java SubnetEnter the ip address:138.101.114.250IP in Binary is10001010011001010111001011111010Enter the number of addresses:26Number of bits reqd for address=5the subnet mask is=27Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3at Subnet.main(Subnet.java:31)linux@ubuntu:~/Desktop$ ^C这是代码import java.util.Scanner;class Subnet{public static void main(String args[]){Scanner sc=new Scanner(System.in);System.out.print("Enter the ip address:");String ip=sc.nextLine();String split_ip[]=ip.split("\\.");String split_bip[]=new String[4];String bip="";for(int i=0;i<4;i++){split_bip[i]=appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i])));bip+=split_bip[i];}System.out.println("IP in Binary is"+bip);System.out.print("Enter the number of addresses:");int n = sc.nextInt();int bits=(int)Math.ceil(Math.log(n)/Math.log(2));System.out.println("Number of bits reqd for address="+bits);int mask=32-bits;System.out.println("the subnet mask is="+mask);int fbip[]=new int[32];for (int i=0;i<32;i++)fbip[i]=(int)bip.charAt(i)-48;for(int i=31;i>31-bits;i--)fbip[i]&=0;String fip[]={"","",""};for(int i=0;i<32;i++)fip[i/8]=new String(fip[i/8]+fbip[i]);System.out.print("Subnet address is=");for(int i=0;i<4;i++){System.out.print(Integer.parseInt(fip[i],2));if(i!=3)System.out.print(".");}System.out.println();int lbip[]=new int[32];for(int i=0;i<32;i++)lbip[i]=(int)bip.charAt(i)-48;for(int i=31;i>31-bits;i--)lbip[i]|=1;String lip[]={"","",""};for(int i=0;i<32;i++)lip[i/8]=new String(lip[i/8]+lbip[i]);System.out.print("Broadcast address is=");for(int i=0;i<4;i++){System.out.print(Integer.parseInt(lip[i],2));if(i!=3)System.out.print(".");}System.out.println();}static String appendZeros(String s){String temp=new String("00000000");return temp.substring(s.length())+s;}}这只是一个非常小的错误,但我不知道在哪里。
2 回答
浮云间
TA贡献1829条经验 获得超4个赞
ArrayIndexOutOfBoundsException 意味着您正在尝试访问数组中不存在的元素,即索引大于最后一个元素索引的元素。
String[] someArray = new String[]{"a - index 0", "b - index 1", "c - index 2"};
String inexistent = someArray[3]; //This will throw an ArrayIndexOutOfBoundsException since there are only three elements in the array, the last having index 2 (it always starts at 0 = zero-based)
你的错误是
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Subnet.main(Subnet.java:31)
你应该看看Subnet.java文件的第 31 行,看看你是如何计算数组索引的
在该行添加断点并检查数组和计算出的索引肯定会有所帮助
料青山看我应如是
TA贡献1772条经验 获得超8个赞
我终于发现了一个小错误:
String fip[]={"","",""};
它位于完整代码的中间。问题是我提交了 4 个字符串,但在上面的错误代码行中,我只让它需要 3 个,答案是我应该再添加一个括号,所以总共 4 个,如下所示:
String fip[]={"","","",""};
添加回答
举报
0/150
提交
取消