Java索引超出范围:0

时间:2016-01-03 03:40:39

标签: java

我正在拼命想办法阻止"字符串索引超出范围:0"错误......只要我不输入任何内容然后继续执行,就会发生错误:

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(0)

这将有助于(示例):

if(ref.charAt(aNumber)==null) { 
    // display error message 
}

2 个答案:

答案 0 :(得分:4)

你的问题在这里:

ref.charAt(i)=='\0'

如果ref是零长度字符串,会发生什么?在这种情况下,尝试访问索引0处的字符(通常是第一个字符)会给您index out of range: 0错误。确保首先测试字符串长度:

if (ref != null && !ref.isEmpty() &&ref.charAt(i)=='\0')  { .. }

答案 1 :(得分:3)

添加length()支票

当您没有输入任何内容时,

ref为空(即"")。因此,您无法在0(或123 ...)获得该角色。您可以在if上添加length检查,例如

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");
}

正则表达式

使用正则表达式编译(可重用)Pattern以验证您的引用标准(2个字母,后跟3个数字,后跟b或n)可能更简单。像,

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");         
}