数组索引越界异常 (Java) [英] Array Index Out of Bounds Exception (Java)

查看:44
本文介绍了数组索引越界异常 (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

public class countChar {

    public static void main(String[] args) {
        int i;
        String userInput = new String();

        userInput = Input.getString("Please enter a sentence");

        int[] total = totalChars(userInput.toLowerCase());

        for (i = 0; i < total.length; i++);
        {
            if (total[i] != 0) {
                System.out.println("Letter" + (char) ('a' + i) + " count =" + total[i]);
            }
        }
    }

    public static int[] totalChars(String userInput) {
        int[] total = new int[26];
        int i;
        for (i = 0; i < userInput.length(); i++) {
            if (Character.isLetter(userInput.charAt(i))) {
                total[userInput.charAt(i) - 'a']++;
            }
        }
        return total;
    }
}

该程序的目的是向用户询问一个字符串,然后计算该字符串中每个字符被使用的次数.

The program's purpose is to ask the user for a string, and then count the number of times each character is used in the string.

当我去编译程序时,它运行良好.当我运行程序时,我可以在弹出框中输入一个字符串,但是在我提交字符串并按 OK 后,我收到一个错误,说

When I go to compile the program, it works fine. When I run the program, I am able to enter a string in the popup box, but after I submit the string and press OK, I get an error, saying

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at countChar.main(countChar.java:14)

我不完全确定问题是什么或如何解决它.

I'm not completely sure what the problem is or how to fix it.

推荐答案

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

使用这个分号,循环循环直到 i == total.length,什么都不做,然后你认为是循环体的执行.

With this semi-colon, the loop loops until i == total.length, doing nothing, and then what you thought was the body of the loop is executed.

这篇关于数组索引越界异常 (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆