[英]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. 我在使用joptionpane获取用户的邮政编码时遇到问题。 I'm trying to check if the format is in L#L#L#L where L is a letter and # is a number.
我正在尝试检查格式是否为L#L#L#L,其中L是字母,而#是数字。 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.
如果我寻找一个不存在的字符串,即string.charAt(5),但我不知所措,但我不知道如何解决它。
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. 编辑:有关更简洁的正则表达式,请参见下面的deanosaur的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.