I'm taking my very first java class. I need to ask for a zip code. I know how to ask for new input if they don't enter 5 digits, but how do I also ask for new input if they enter a non-integer?
Here is what I have:
import java.util.Scanner;
public class AndrewDemographics {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int zip; // 5 digit zip
System.out.print("Enter your 5 digit zip code: ");
zip = stdIn.nextInt();
while ((zip < 10000) || (zip > 99999)) {
// error message
System.out.println("Invalid Zip Code format.");
System.out.println("");
System.out.println("Enter your 5 digit zip code: ");
zip = stdIn.nextInt();
} //end if zip code is valid
}
}
To support zip codes starting with 0
, you need to store the zip code in a String, and then it's easiest to validate it using a regex:
Scanner stdIn = new Scanner(System.in);
String zip;
do {
System.out.print("Enter your 5 digit zip code: ");
zip = stdIn.next();
} while (! zip.matches("[0-9]{5}"));
If you want to print error message, you can do it like this, which uses nextLine()
so simply pressing enter will print error message too:
Scanner stdIn = new Scanner(System.in);
String zip;
for (;;) {
System.out.print("Enter your 5 digit zip code: ");
zip = stdIn.nextLine().trim();
if (zip.matches("[0-9]{5}"))
break;
System.out.println("Invalid Zip Code format.");
System.out.println();
}
As the comment suggests, you will need to take into account zip code starting with zero. I guess for that, you'll need to consider the input as a String:
- check if the
String
is 5 characters long (to match the 5 digits) String
does not contain+
sign as+1234
would work- check if the
String
is a valid integer - check if the
Integer
is positive as-1234
would be still valid - you now have something between 00000 and 99999
In practice
public static void main(String[] args){
Scanner stdIn = new Scanner(System.in);
String userInput;
int zipCode = -1;
// flag to stop spamming the user
boolean isValid = false;
while (!isValid) {
// ask the user
System.out.print("Enter your 5 digit zip code: ");
userInput = stdIn.next();
// it should be 5 digits so 5 charaters long:
if (userInput.length() == 5 && !userInput.contains("+")) {
try {
zipCode = Integer.parseInt(userInput);
if (zipCode > 0) {
isValid = true;
}
}
catch (NumberFormatException e) {
// do nothing
}
}
System.out.println("Zip code is invalid!");
}
System.out.println("You have selected the zip code: " + zipCode);
}
There is an issue with zip codes with leading zeros in previous. There needs to be a check if both is a number and is 5 characters in length. A zero leading zip would be 4 digits in length if read in as a number type.
Top of my head:
String zip = null;
do {
zip = stdIn.next();
try {
Integer.parseInt(zip); // this will throw exception if not a number
} catch (NumberFormatException e) {
continue; // this will start the next loop iteration if not a number
}
} while (zip.length() != 5); // this will start the next iteration if not 5 characters
I took the input as a String using nextLine()
rather than an int because it accounts for zip codes starting with 0, and a zip code, although written numerically, isn't really a numerical value. I felt that the easiest way to structure the if/else statements determining if the zip code was valid was to use return statements that would break out of the checks at the return, so I wrote a method that would check for the validity of the zip code:
public static boolean checkValidZip(String zip) {
if (zip.length() != 5) { //invalid if not 5 chars long
return false;
}
for (int i=0; i<zip.length(); i++) { //invalid if not all digits
if (!Character.isDigit(zip.charAt(i))) {
return false;
}
}
return true; //valid if 5 digits
}
The main method then, looks like this:
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
String zip = ""; //5 digit zip
boolean valid = false;
boolean allNums = true;
while (!valid) {
System.out.print("Enter your 5 digit zip code: ");
zip = stdIn.nextLine();
valid = checkValidZip(zip);
if (!valid) {
System.out.println("Invalid Zip Code format.");
System.out.println("");
}
}
//end if zip code valid
}
来源:https://stackoverflow.com/questions/46590539/validate-an-integer-and-make-it-5-digits