fork download
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3. import java.util.Scanner;
  4.  
  5. class Solution{
  6. public static void main(String[] args){
  7. Scanner in = new Scanner(System.in);
  8. while(in.hasNext()){
  9. String IP = in.next();
  10. System.out.println("IP->"+isValidIP(IP));
  11. }
  12. }
  13.  
  14. public static boolean isValidIP(String IP){
  15. String [] parts = IP.split("\\.");
  16.  
  17. // check for exactly 4 parts
  18. if(parts.length!=4){
  19. return false;
  20. }
  21.  
  22. for(String part :parts){
  23. // check if numeric
  24. if(!part.matches("\\d+")){
  25. return false;
  26. }
  27.  
  28. // parse to int
  29. int num = Integer.parseInt(part);
  30.  
  31. // check range
  32. if(num <0 || num > 255){
  33. return false;
  34. }
  35. }
  36.  
  37. return true;
  38. }
  39. }
Success #stdin #stdout 0.13s 56868KB
stdin
1.1.1.1
128.230.124.124
127.0.0.1
256.2.4.10
.4.1.8.8
stdout
IP->true
IP->true
IP->true
IP->false
IP->false