数组基于用户输入,错误?

时间:2013-07-11 13:14:37

标签: java arrays

我多次查看此代码,我真的无法理解为什么会出现错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at qrt2.practice.main(practice.java:34)

我正在使用Eclips标准SDK

,代码是:

package qrt2;
import javax.swing.*;

public class practice {

        public static void main(String[] args) {

//creating JOption for the input

            String num1 = JOptionPane.showInputDialog("Enter the first number");
            int x = Integer.parseInt(num1);

            String num2 = JOptionPane.showInputDialog("Enter the first number");
            int y = Integer.parseInt(num2);

            String num3 = JOptionPane.showInputDialog("Enter the first number");
            int z = Integer.parseInt(num3);

            String num4 = JOptionPane.showInputDialog("Enter the first number");
            int v = Integer.parseInt(num4);

            String num5 = JOptionPane.showInputDialog("Enter the first number");
            int h = Integer.parseInt(num5);

            String num6 = JOptionPane.showInputDialog("Enter the first number");
            int k = Integer.parseInt(num6);


//creating array

            int [] ary = new int []{x,y,z,v,h,k};
            int counter;
            for( counter=0;counter<ary.length;counter++);
            System.out.println(counter + " " + ary[counter]);

        }
}

4 个答案:

答案 0 :(得分:2)

for语句

中删除尾部分号
for (counter = 0; counter < ary.length; counter++);
                                                  ^

一旦到达此声明,将分号保留在counter等于ary.length

System.out.println(counter + " " + ary[counter]);

由于数组为零,这将导致ArrayIndexOutOfBoundsException

除非在循环外需要变量counter,否则将其移入for语句初始化部分,如下所示

for (int counter=0; counter < ary.length; counter++) {
    System.out.println(counter + " " + ary[counter]);
}

这将使ary[counter]表达式立即显示编译失败。另请注意,括号可以明确范围。

答案 1 :(得分:2)

for(counter=0;counter<ary.length;counter++) {
    System.out.println(counter + " " + ary[counter]);
}

取下分号并用卷曲的开口支架替换它。然后在输出后关闭花括号。

如果你想应用最佳实践,你还应该在循环中声明你的计数器变量,如下所示:

for(int counter = 0; counter < ary.length; counter++) {}

答案 2 :(得分:1)

从for循环中删除分号。

for (counter = 0; counter < ary.length; counter++)
{
}

答案 3 :(得分:1)

你的问题在于以下几点:

for( counter=0;counter<ary.length;counter++);
System.out.println(counter + " " + ary[counter]);

具体来说,第一个完成循环,第二个打印一行 - 循环完成后计数器增加超出数组的长度(从而突破循环)。你需要的是在循环内打印,所以这两行应该是:

for( counter=0;counter<ary.length;counter++)
    System.out.println(counter + " " + ary[counter]);

(注意在第一行末尾删除分号)。或者,使其更加清晰:

for( counter=0;counter<ary.length;counter++) {
    System.out.println(counter + " " + ary[counter]);
}