[英]How to check if a correct character was entered by a user in a string in java?
[英]How to check if a string is in the correct input when entered?
我在使用joptionpane獲取用戶的郵政編碼時遇到問題。 我正在嘗試檢查格式是否為L#L#L#L,其中L是字母,而#是數字。 我正在嘗試提供錯誤檢查,以查看郵政編碼是否采用這種格式。 如果我尋找一個不存在的字符串,即string.charAt(5),但我不知所措,但我不知道如何解決它。
這是我正在錯誤的當前代碼
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 {
}
有幾種解決方案。 一種方法是首先驗證輸入的大小:
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 {
}
另一個方法是使用正則表達式:
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 {
}
編輯:有關更簡潔的正則表達式,請參見下面的deanosaur的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.