GeeksforGeeks Sudo Placement: Validate an IP Address in Java

The code is written in java. The output that is generated is correct, I have corrected the code on their page which is already written, It was generating error on submit,so I thought to publish the code here. The code ask to validate an IP address, that the given ip address falls on the condition of IPv4 specification.

The questions says:

Write a program to Validate an IPv4 Address. According to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1 . The generalized form of an IPv4 address is (0-255).(0-255).(0-255).(0-255). Here we are considering numbers only from 0 to 255 and any additional leading zeroes will be considered invalid.

Your task is  to complete the function isValid which returns 1 if the ip address is valid else returns 0. The function takes a string ip as its only argument .

Input:
The first line of each test case contains an integer T denoting the number of test case . Then T test cases follow . Each test case takes a string ip.

Output:
For each test case output will be 1 if the string is a valid ip address else 0.

Constraints:
1<=T<=100
1<=length of string <=50

Example(To be used only for expected output) :
Input

4
222.111.111.111
5555..555
0000.0000.0000.0000
1.2.3.04

Output
1
0
0
0

CODE:
import java.util.*;
import java.io.*;
public class validip {
public static void main(String[] args){
Scanner sc= new Scanner (System.in);
//System.out.println("Enter test cases: ");
int t = sc.nextInt();
while(t-->0){
//System.out.println("Enter the string:");
String s = sc.next();
Solution obj = new Solution();

if (obj.isValidIP(s))
System.out.println(1);
else
System.out.println(0);
}
}
}

/*Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above.*/

//User function Template for Java
class Solution {
public boolean isValidIP(String s){
int num=-1,j=1,t=1;
String[] arr= s.split("");
String d=new String();
for(int i=0;i<arr.length;i++){

if(s.charAt(i) != '.'){
d=d.concat(arr[i]);
}

if(s.charAt(i) == '.'){
j++;
if(d!=null){
num=Integer.parseInt(d);
}
if(num >255){
j=0;
break;
}else{
t++;d="";
}
}

}
if(j==4 && t==4){
return true;
}else{
return false;
}

}

}

OUTPUT:

Validate an IP in java

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: