2013-10-04 70 views
0

我得到這個錯誤:檢查,如果兩組數字相等錯誤

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 

這指的是這行代碼if(x[k]==y[j])

Scanner sc1 = new Scanner(System.in);   
    int [] x; 
    int [] y; 
    int size; 
    System.out.println("Numbers in launch code sequence should be entered on "); 
    System.out.println("single line, separated by blanks."); 
    System.out.println(""); 
    System.out.println("Enter length of launch code sequence: ");   
    size = sc1.nextInt(); 
    x = new int[size]; 
    y = new int[size]; 
    int k = 0; 
    int j = 0; 
    System.out.println("Mr. President, Enter the launch code sequence: "); 
    for(;k<x.length; k++){   
    x[k] = sc1.nextInt();} 
    System.out.println("Mr. Vice President, Enter the launch code sequence"); 
    for(;j<y.length; j++){ 
    y[j] = sc1.nextInt();  
      if(x[k]==y[j]){ 
       System.out.println("All equal: Missile system cleared for launch."); 

      if(x[k]!=y[j]){ 
       System.out.println("Codes do not check out. Abort missile launch."); 
      } 
     } 
    } 
} 
+1

在行代碼 - >如果(X [k]的==ÿ [j]){ 你的k已經達到了x.length,所以它超出了界限。 – wxyz

+1

適當的縮進有助於理解代碼的控制流程。如果你格式正確,你一定會發現你自己的錯誤。 – thSoft

+1

我希望代碼不會因爲一些錯誤而啓動實際的導彈,並且會導致我們所知道的生命結束。那真的會毀了我的一天。 – NickJ

回答

0

您的代碼

  • 遍歷X數組的;之後,k == x.length
  • 迭代y數組;本次迭代裏面,你用X比較[K],這是出界對於x

我猜你真的想要做的是兩個嵌套的循環 - 在這種情況下,改變

for(;k<x.length; k++){   
    x[k] = sc1.nextInt();} 

for(;k<x.length; k++){   
    x[k] = sc1.nextInt(); 

和y循環之後添加結束}

+0

非常感謝。這讓我更接近最終產品。它不再給我一個錯誤信息。我現在唯一的問題是,如果我輸入2組數字,其中1組的數字與另一組數字不同,它仍然表示它們是相同的組合!我能做什麼? – user2845710

+0

每當單個*字符*匹配時,您正在打印「全部相同」消息。如果遇到錯誤的字符,我建議你設置一個「不匹配」標誌,並在循環之後打印一條消息,告訴用戶匹配是否成功。 –

0

在這個階段

if(x[k]==y[j]){ 

k已完成遍歷其數組,並將設置爲x.length

,因此出界

0

在完成加載代碼後,您應該將k的值重置爲0。或者你可以在循環頭文件中定義它。

for(int k = 0; k < x.length; k++) 
{ 
    // Your code here. 
} 
0

在此之後的for循環完成:k的

for(;k<x.length; k++){   
    x[k] = sc1.nextInt();} 

值將x.length

k == x.length //will be true. because the k will be incremented and the condition k<x.length will be checked. this is how the for loop functions 

,並在接下來的for循環您正在訪問

x[k] // equivlent of x[x.length] which is out of abounds 

你是最大的索引欠訪問是x[x.length-1]因爲在Java數組索引從0

因此開始異常的ArrayIndexOutOfBounds中,x [K]將出界