Write a java program to check IP Validator.

Write a program to read a string and validate the IP address. Print “Valid” if the IP address is valid, else print “Invalid”.

Input and Output Format:

Input consists of a string that corresponds to an IP.

The output consists of a string(“Valid” or “Invalid”).

Refer sample output for formatting specifications.

 

Note: An IP address has the format a.b.c.d where a,b,c,d are numbers between 0-255.

Sample Input 1:

132.145.184.210

Sample Output 1:

Valid

Sample Input 2:

132.145.184.290

Sample Output 2:

Invalid

Check IP Validator in Java.

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    
    String ipAddress = sc.nextLine();
    boolean b = validateIpAddress(ipAddress);
    if (b == true)
      System.out.println("Valid");
    else
      System.out.println("Invalid");
  }

  public static boolean validateIpAddress(String ipAddress) {
    boolean b1 = false;
    StringTokenizer t = new StringTokenizer(ipAddress, ".");
    int a = Integer.parseInt(t.nextToken());
    int b = Integer.parseInt(t.nextToken());
    int c = Integer.parseInt(t.nextToken());
    int d = Integer.parseInt(t.nextToken());
    if ((a >= 0 && a <= 255) && (b >= 0 && b <= 255)
        && (c >= 0 && c <= 255) && (d >= 0 && d <= 255))
      b1 = true;
    return b1;
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

six + 11 =