2014-12-22 104 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進行檢查,它更安全。