2014-12-22 84 views
1

我是Java新手,这可能是一个愚蠢的问题,但我真的需要你的帮助。字符串数组抛出错误 - 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) 

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

有人能告诉我我的错误在哪里,为什么它不工作?

回答

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 
     } 
    } 

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

the错误是在这里

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

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

因为列数组是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()

,以获取有关这个第2期更多的解释,你一定要读这问题跳过nextLine() after use nextInt()

+3

或更好:'x

+0

感谢您的最快回复但1st回路正常工作。当循环2开始不允许我输入Name时,它直接变老。你知道为什么吗? – user3114645

+0

@ user3114645 - 这是一个不同的错误。当你使用'sc.nextInt()'时,你会得到每个字符,直到你按回车(但不是返回字符本身)。那么下次你调用'sc.nextLine()'时,它只能保存返回字符而没有别的。正确刷新的方法是简单地调用'sc.nextLine()',并且不要在每次调用'sc.nextInt()'后存储它。 – NoseKnowsAll

0

在Java的许多编程语言,计数从0开始,所以数组长度3,当电脑开始计数时:0,1,2而不是1,2,3。一般规则是:数组长度 - 1.

由于您正在使用数组,因此使用属性length进行检查,它更安全。