简体   繁体   中英

How to check if a string is in the correct input when entered?

I have a problem where i'm using a joptionpane to get the postal code of a user. I'm trying to check if the format is in L#L#L#L where L is a letter and # is a number. I'm trying to provide error checks to see if the postal code is in that format. I keep getting out of bounds errors if i look for a string that doesn't exist ie string.charAt(5) but I don't know how to fix it.

this is the current code that i'm erroring at

String postalCode = JOptionPane.showInputDialog("Enter customer(s) " + (count + 1) + " postal code");

if (Character.isLetter(postalCode.charAt(0)) && 
    Character.isDigit(postalCode.charAt(1)) && 
    Character.isLetter(postalCode.charAt(2)) && 
    Character.isDigit(postalCode.charAt(3)) && 
    Character.isLetter(postalCode.charAt(4)) && 
    Character.isDigit(postalCode.charAt(5))) {
} 
else {
}

There are a couple solutions. One would be to first validate the size of the input:

String postalCode = JOptionPane.showInputDialog("Enter customer(s) " + (count + 1) + " postal code");

if ((postalCode.length() == 7) && Character.isLetter(postalCode.charAt(0)) && Character.isDigit(postalCode.charAt(1)) && Character.isLetter(postalCode.charAt(2)) && Character.isDigit(postalCode.charAt(3)) && Character.isLetter(postalCode.charAt(4)) && Character.isDigit(postalCode.charAt(5))) {

} else {
}

Another would be to use a regular expression:

import java.util.regex.Pattern;
...
String postalCode = JOptionPane.showInputDialog("Enter customer(s) " + (count + 1) + " postal code");
if (Pattern.matches("^[a-zA-Z]\\d[a-zA-Z]\\d[a-zA-Z]\\d[a-zA-Z]$", postalCode)) {

} else {
}

Edit: See deanosaur's comment below for a more concise regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM