JAVA类 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
import java.util.Arrays; import java.util.Scanner; class IP{ int[] ip_array = new int[4]; int[] mask_array = new int[4]; public String ip_class; public boolean is_private; String mask2bi(int mask){ StringBuffer sb = new StringBuffer(Integer.toBinaryString(mask)); while(sb.length()!=8){ sb.insert(0,'0'); } return sb.toString(); } IP(String ip, String mask){ String[] ip_string_array = ip.split("\\."); String[] masks_string_array = mask.split("\\."); boolean mask_0 = false; if(ip_string_array.length!=4 || masks_string_array.length!=4) { ip_class = "invalid"; }else{ for(int i=0;i<4;i++){ try{ int ip_parse = Integer.valueOf(ip_string_array[i]); int mask_parse = Integer.valueOf(masks_string_array[i]); ip_array[i] = ip_parse; mask_array[i] = mask_parse; if (ip_array[0]==0 || ip_array[0]==127) throw new Exception("non-count"); if(ip_parse<0 || ip_parse>255 || mask_parse<0 || mask_parse>255) throw new Exception(""); for(char c : mask2bi(mask_parse).toCharArray()){ if(c=='0') { mask_0=true; }else if(mask_0==true) throw new Exception(""); } }catch (Exception e){ if(e.getMessage() == "non-count") ip_class = "non-count"; else ip_class = "invalid"; return; } } int mask_sum = Arrays.stream(mask_array).sum(); if(mask_sum==0 || mask_sum==255*4) { ip_class = "invalid"; }else{ if (ip_array[0]<=126) { ip_class = "A"; }else if (ip_array[0]>=128 && ip_array[0]<=191) { ip_class = "B"; }else if (ip_array[0]>=192 && ip_array[0]<=223) { ip_class = "C"; }else if (ip_array[0]>=224 && ip_array[0]<=239) { ip_class = "D"; }else if (ip_array[0]>=240) { ip_class = "E"; } if(ip_array[0]==10 || (ip_array[0]==172 && ip_array[1]>=16 && ip_array[1]<=31) || (ip_array[0]==192 &&ip_array[1]==168)){ is_private = true; }else{ is_private = false; } } } } } // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int A=0,B=0,C=0,D=0,E=0,Invalid=0,Private=0; // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String line = in.nextLine(); if(line.equals(""))break; String[] line_split = line.split("~"); IP ip = new IP(line_split[0],line_split[1]); switch (ip.ip_class){ case "A": A++; break; case "B": B++; break; case "C": C++; break; case "D": D++; break; case "E": E++; break; case "invalid": Invalid++; break; } if(ip.is_private)Private++; } System.out.print(A); System.out.print(" "); System.out.print(B); System.out.print(" "); System.out.print(C); System.out.print(" "); System.out.print(D); System.out.print(" "); System.out.print(E); System.out.print(" "); System.out.print(Invalid); System.out.print(" "); System.out.print(Private); } }
多多使用类的方法练习