t805

IP to Decimal Notation

Sep 10th, 2014
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. /**
  2. * Title: IP To Decimal
  3. * Author: Sher Stark
  4. * Date: 3 September 2014
  5. */
  6.  
  7. package assignment1;
  8.  
  9. import java.util.Scanner;
  10.  
  11. public class Question2() {
  12.  
  13.     public static void main(String[] args) {
  14.  
  15.         Scanner input = new Scanner(System.in);
  16.  
  17.         String ip;
  18.         String ipArray[];
  19.         long decimal = 0;
  20.         int num = 0;
  21.  
  22.         do {
  23.             System.out.print("Enter an IP address: ");
  24.             ip = input.nextLine();
  25.    
  26.             ipArray = ip.split("\\.");
  27.         }while(!ValidateLength(ipArray)||!ValidateRange(ipArray));
  28.  
  29.         decimal = GetDecimal(ipArray);
  30.  
  31.         PrintDecimal(decimal);
  32.     }
  33.  
  34.     static boolean ValidateLength(String ipArray[]) {
  35.  
  36.         if(ipArray.length != 4) {
  37.             System.out.println("Invalid IPv4 format. Please try again!");
  38.             return false;
  39.         }
  40.         else
  41.             return true;
  42.     }
  43.        
  44.     static boolean ValidateRange(String ipArray[]) {
  45.  
  46.         for(int i = 0; i < ipArray.length; i++) {
  47.  
  48.             int num = Integer.parseInt(ipArray[i]);
  49.  
  50.             if(num < 0 || num > 255) {
  51.                 System.out.println("Invalid. Please use a number between 0-255 for each component.");
  52.                 return false;
  53.             }
  54.         }
  55.  
  56.         return true;
  57.     }
  58.    
  59.     static long GetDecimal(String ipArray[]) {
  60.    
  61.         long decimal = 0;
  62.  
  63.         for(int i = 0; i < ipArray.length; i++) {
  64.  
  65.             int exponent = 3 - i;
  66.  
  67.             int temp = Integer.parseInt(ipArray[i]);
  68.             decimal += temp * (Math.pow(256, exponent));
  69.         }
  70.  
  71.         return decimal;
  72.     }
  73.  
  74.     static void PrintDecimal(long decimal) {
  75.        
  76.         System.out.println("The decimal notation is: " + decimal);
  77.     }
Advertisement
Add Comment
Please, Sign In to add comment