In: Computer Science
Write a program to validate Canadian Postal Codes. A postal code must follow the pattern of L9L9L9 where:
Your program should continue accepting postal codes until the user enters the word “exit”.
Sample run (user input is shown in bold underline):
Enter a postal code: T2T-3X7
Postal code wrong length, format L9L9L9
Enter a postal code: T2T3AA
Postal code has letters where there are supposed to be digits
Enter a postal code: T2T358
Postal code has digits where there are supposed to be letters
Enter a postal code: T2T3A8
Postal code is valid!
Enter a postal code: exit
please answer in java
PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR YOU
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String choice = "yes";
//loops until the choice is exit
while (!choice.equals("exit")) {
//Ask user for postal code
System.out.print("Enter postal code: ");
String code = s.next();
//Find length of code
int len = code.length();
if (len != 6) {
System.out.println("Postal code wrong length, format L9L9L9");
} else {
int letter = 0;
int digit = 0;
for (int i = 0; i < len; i++) {
//Check if char is letter
if (!Character.isDigit(code.charAt(i))) {
letter++;
}
//Check if char is digit
if (Character.isDigit(code.charAt(i))) {
digit++;
}
}
//Check as per validation rules defined
if (letter == 3 && digit == 3) {
System.out.println("Postal code is valid!");
} else if (letter < 3 && digit > 3) {
System.out.println(
"Postal code has digits where there are supposed to be letters"
);
} else if (letter > 3 && digit < 3) {
System.out.println(
"Postal code has letters where there are supposed to be digits"
);
}
}
System.out.print("Want to enter more postal code, yes/exit: ");
choice = s.next();
}
}
}