I need to print a hypothetical IP address. I must print if all 4 octets are within range, but I do not know how to print if 1 or more octets aren't.
My teacher's instructions:
You are going to write a program that will accept 4 integer numbers from a user, check to see if they are valid IP address range numbers
(1 - 255).(0 - 255).(0 - 255).(1 - 254)and then if they are valid you will put them in the correct dotted decimal notation for an IP address. If they are invalid, tell the user which one is invalid.Sample Run:
Please enter the first Octet: 125 Please enter the second Octet: 10 Please enter the third Octet: 52 Please enter the fourth Octet: 10 IP Address: 125.10.52.10Sample Run:
Please enter the first Octet: 125 Please enter the second Octet: 10 Please enter the third Octet: 520 Please enter the fourth Octet: 10 Octet three is incorrect.
What I have tried:
System.out.println("Please enter the first Octet:");
int oct1;
oct1 = scan.nextInt();
System.out.println("Please enter the second Octet:");
int oct2;
oct2 = scan.nextInt();
System.out.println("Please enter the third Octet:");
int oct3;
oct3 = scan.nextInt();
System.out.println("Please enter the fourth Octet:");
int oct4;
oct4 = scan.nextInt();
if (oct1 >= 1 && oct1 <= 255);{
System.out.println("Octet one is invalid.");
}
if (oct2 >= 0 && oct2 <= 255);{
System.out.println("Octet two is invalid.");
}
if (oct3 >= 0 && oct3 <= 255);{
System.out.println("Octet three is invalid.");
}
if (oct4 >= 1 && oct4 <= 254);{
System.out.println("Octet four is invalid.");
}
You have two mistakes in your code.
;, after eachifcondition, for exampleThis means that when the
ifcondition is true, an empty statement will be performed and the line after will always be executed. In other words, it doesn't matter what octet the user enters, the message Octet one is invalid. will always be displayed. You need to remove the semicolon.Your
ifcondition actually checks whether the octet is valid. You need to change that.Finally, your code is missing the the code that displays the actual IP address when all the entered octets are valid.
The below code contains the corrections.