fork download
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3. import java.util.Scanner;
  4. /*
  5. IP address is a string in the form "A.B.C.D",
  6. where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed.
  7.  
  8. Some valid IP address:
  9. 000.12.12.034
  10. 121.234.12.12
  11. 23.45.12.56
  12. Some invalid IP address:
  13. 000.12.234.23.23
  14. 666.666.23.23
  15. .213.123.23.32
  16. 23.45.22.32.
  17. I.Am.not.an.ip
  18.  
  19. Sample Input
  20. 000.12.12.034
  21. 121.234.12.12
  22. 23.45.12.56
  23. 00.12.123.123123.123
  24. 122.23
  25. Hello.IP
  26.  
  27.  
  28. */
  29. class Solution{
  30. public static void main(String[] args){
  31. Scanner in = new Scanner(System.in);
  32. while(in.hasNext()){
  33. String IP = in.next();
  34. System.out.println("Is IP->"+IP+" a valid ip : "+isValidIp(IP));
  35. }
  36. }
  37.  
  38. private static boolean isValidIp(String ipAddress){
  39. if(ipAddress == null || ipAddress.isBlank()){
  40. return false;
  41. }
  42. int length = ipAddress.length();
  43. if(length < 7 || length > 15){
  44. return false;
  45. }
  46. if(ipAddress.indexOf(".") == -1){
  47. return false;
  48. }
  49. String[] delimitedString = ipAddress.split("\\.");
  50. if(delimitedString == null || delimitedString.length != 4){
  51. return false;
  52. }
  53. for(String s : delimitedString){
  54. try{
  55. Integer value = Integer.valueOf(s);
  56. if(value < 0 || value > 255){
  57. return false;
  58. }
  59.  
  60. }
  61. catch(Exception e){
  62. return false;
  63. }
  64. }
  65. return true;
  66. }
  67. }
Success #stdin #stdout 0.17s 58796KB
stdin
1.1.1.1
128.230.124.124
127.0.0.1
256.2.4.10
.4.1.8.8
000.12.12.034
121.234.12.12
23.45.12.56
00.12.123.123123.123
122.23
Hello.IP
stdout
Is IP->1.1.1.1 a valid ip : true
Is IP->128.230.124.124 a valid ip : true
Is IP->127.0.0.1 a valid ip : true
Is IP->256.2.4.10 a valid ip : false
Is IP->.4.1.8.8 a valid ip : false
Is IP->000.12.12.034 a valid ip : true
Is IP->121.234.12.12 a valid ip : true
Is IP->23.45.12.56 a valid ip : true
Is IP->00.12.123.123123.123 a valid ip : false
Is IP->122.23 a valid ip : false
Is IP->Hello.IP a valid ip : false