Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Title: IP To Decimal
- * Author: Sher Stark
- * Date: 3 September 2014
- */
- package assignment1;
- import java.util.Scanner;
- public class Question2() {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- String ip;
- String ipArray[];
- long decimal = 0;
- int num = 0;
- do {
- System.out.print("Enter an IP address: ");
- ip = input.nextLine();
- ipArray = ip.split("\\.");
- }while(!ValidateLength(ipArray)||!ValidateRange(ipArray));
- decimal = GetDecimal(ipArray);
- PrintDecimal(decimal);
- }
- static boolean ValidateLength(String ipArray[]) {
- if(ipArray.length != 4) {
- System.out.println("Invalid IPv4 format. Please try again!");
- return false;
- }
- else
- return true;
- }
- static boolean ValidateRange(String ipArray[]) {
- for(int i = 0; i < ipArray.length; i++) {
- int num = Integer.parseInt(ipArray[i]);
- if(num < 0 || num > 255) {
- System.out.println("Invalid. Please use a number between 0-255 for each component.");
- return false;
- }
- }
- return true;
- }
- static long GetDecimal(String ipArray[]) {
- long decimal = 0;
- for(int i = 0; i < ipArray.length; i++) {
- int exponent = 3 - i;
- int temp = Integer.parseInt(ipArray[i]);
- decimal += temp * (Math.pow(256, exponent));
- }
- return decimal;
- }
- static void PrintDecimal(long decimal) {
- System.out.println("The decimal notation is: " + decimal);
- }
Advertisement
Add Comment
Please, Sign In to add comment