Java-索引超出范围:0
我正在拼命地想办法阻止“字符串索引超出范围:0”错误。。。每当我没有输入任何内容,然后继续执行时,就会发生这种情况:Java-索引超出范围:0,java,Java,我正在拼命地想办法阻止“字符串索引超出范围:0”错误。。。每当我没有输入任何内容,然后继续执行时,就会发生这种情况: static String getRef(Scanner Keyboard) { Scanner keyboard = new Scanner(System.in); String ref= ""; boolean valid = false; int errors = 0; boolean problem
static String getRef(Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
String ref= "";
boolean valid = false;
int errors = 0;
boolean problem = false;
while(valid==false)
{
System.out.println("Please enter a reference number which is two letters followed by three digits and a letter(B for business accounts and N for non business accounts)");
ref = keyboard.nextLine();
for (int i=0; i<6; i++)
{
if (ref.charAt(i)=='\0')
{
problem = true;
}
}
if(problem == true)
{
System.out.println("The reference must consist of 6 Characters");
}
else
{
if ((Character.isDigit(ref.charAt(0))== true) || (Character.isDigit(ref.charAt(1))== true))
{
System.out.println("The first 2 characters must be letters");
errors = errors + 1;
}
if ((Character.isDigit(ref.charAt(2))== false) || (Character.isDigit(ref.charAt(3))== false)||(Character.isDigit(ref.charAt(4))== false))
{
System.out.println("The 3rd,4th and 5th characters must be numbers");
errors = errors + 1;
}
if ((!ref.toUpperCase().endsWith("B"))&&(!ref.toUpperCase().endsWith("N")))
{
System.out.println("The 6th character must be either B(for business accounts) or N(for non business accounts) ");
errors = errors + 1;
}
if (errors==0)
{
valid=true;
}
}
}
return ref;
}
你的问题是:
ref.charAt(i)=='\0'
如果ref
是长度为零的字符串,会发生什么情况?在这种情况下,尝试访问索引0处的字符(第一个字符通常位于该位置)将导致索引超出范围:0
错误。确保首先测试字符串长度:
if (ref != null && !ref.isEmpty() &&ref.charAt(i)=='\0') { .. }
添加length()
检查
当您不输入任何内容时,ref
为空(即”
)。因此,您无法在0
(或1
,2
,3
…)处获取字符。如果检查长度
,则可以添加,如
if (ref.length() > 5) {
for (int i = 0; i < 6; i++) {
if (ref.charAt(i) == '\0') {
problem = true;
}
}
} else {
System.out.println("Please enter at least 6 characters");
}
嗯,我不会用\\D{2}
来验证字母…:PIf OP希望只接受拉丁字母,那么这是可以的,但是如果他喜欢接受更多类型的字母,那么Pattern
提供了\p{L}
,它接受每个Unicode字母。为什么使用6。您不能只使用string.length进行相同的操作,然后在那里进行逻辑操作。可能存在重复的情况,您为什么要检查'\0'
的键盘输入<代码>字符串
在Java中不是以null结尾的。
if (ref.length() > 5) {
for (int i = 0; i < 6; i++) {
if (ref.charAt(i) == '\0') {
problem = true;
}
}
} else {
System.out.println("Please enter at least 6 characters");
}
String ref; // <-- get input
Pattern p = Pattern.compile("([a-zA-Z]{2})(\\d{3})([B|N|b|n])");
Matcher m = p.matcher(ref);
if (m.matches()) { // <-- valid = m.matches();
System.out.println("ref is valid");
} else {
System.out.println("ref is not valid");
}