String Array抛出错误-Java

时间:2014-12-22 15:29:39

标签: java netbeans indexoutofboundsexception

我是Java的新手,这可能是一个愚蠢的问题,但我真的需要你的帮助。

代码:

String str[] ={"Enter your name","Enter your age","Enter your salary"};
        Scanner sc = new Scanner(System.in);
        int[] i = new int[2];
        String[] s = new String[2];
        int[] y = new int[2];
        for(int x = 0  ; x <= 2 ; x++)
        {
            System.out.println(str[0]);
            s[x] = sc.nextLine();
            System.out.println(s[x]);

            System.out.println(str[1]);
            i[x]=sc.nextInt();
            System.out.println(i[x]);

            System.out.println(str[2]);
            y[x]=sc.nextInt();
            System.out.println(y[x]);
        }

输出 :

run:
Enter your name
Sathish
Sathish
Enter your age
26
26
Enter your salary
25000
25000
Enter your name

Enter your age
23
23
Enter your salary
456
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at javaapplication1.JavaApplication1.main(JavaApplication1.java:121)
456
Enter your name
Java Result: 1
BUILD SUCCESSFUL (total time: 34 seconds)

注意:第一个循环正常工作。然后它会抛出错误。

有人可以告诉我我的错误在哪里以及为什么它不起作用?

2 个答案:

答案 0 :(得分:5)

此行生成错误

for(int x = 0  ; x <= 2 ; x++)

更改为

for(int x = 0  ; x < 2 ; x++)

完整代码

   public static void main(String[] args) {
        String str[] = {"Enter your name", "Enter your age", "Enter your salary"};
        Scanner sc = new Scanner(System.in);
        int[] i = new int[2];
        String[] s = new String[2];
        int[] y = new int[2];
        for (int x = 0; x < 2; x++) {
            System.out.println(str[0]);
            s[x] = sc.nextLine();
            System.out.println(s[x]);

            System.out.println(str[1]);
            i[x] = sc.nextInt();
            System.out.println(i[x]);

            System.out.println(str[2]);
            y[x] = sc.nextInt();
            System.out.println(y[x]);
            sc.nextLine();// add this line to skip "\n" Enter key
        }
    }

........................解释...................... ............

错误在这里

for (int x = 0; x =< 2; x++) {

  s[x] = sc.nextLine();// when x=2 error occurs

因为s数组的长度为2且只有2个元素,但数组索引基于零,你不能得到s[2]

,第二个问题是“But 1st loop works correctly. when loop 2 starts its not allowing me to type Name .its directly goes to age .Do you know why ?

以及..

input.nextInt()只读取int值。当您继续使用input.nextLine()阅读时,您会收到“\ n”Enter键。因此,要跳过此步骤,您必须添加input.nextLine()

要获得有关此第二个问题的更多解释,您必须阅读此问题跳过nextLine() after use nextInt()

答案 1 :(得分:0)

在Java中,尽可能多的编程语言,计数从0开始,因此当计算机开始计数时,长度为3的数组是:0,1,2而不是1,2,3。一般规则是:数组长度 - 1。

在使用数组时,使用属性length进行检查,它更安全。