2013-04-20 84 views
0

我正在從一個程序讀取來自文件的輸入並給出輸出多少個字符串互補的輸出。 這裏是代碼數組索引超出界限的錯誤

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Arrays; 
import java.util.Random; 
import java.util.Scanner; 




public class QuickSorting { 

    /** 
    * @param args 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 
     String data; 
     Boolean status=false; 
     int counter=0; 
     int cases,case_item; 
     String[]inputs; 
     String to_cmp; 
     String with_cmp; 
     // TODO Auto-generated method stub 
     File file = new File("input.txt"); 
     // Get data from this file using a file reader. 
     FileReader fr = new FileReader(file); 
     // To store the contents read via File Reader 
     BufferedReader br = new BufferedReader(fr); 
     //writer to write in file 

     data=br.readLine(); 
     cases=Integer.parseInt(data); 
     //check total cases 
     for(int i=1;i<=cases;i++) 
     { 
      data=br.readLine(); 
      case_item=Integer.parseInt(data.trim()); 
      inputs=new String[case_item]; 
      //check entries in each case 
      for(int c_i=0;c_i<case_item;c_i++) 
      { 
       data=br.readLine(); 
       inputs[c_i]=data; 

      } 

      for(int i1=0;i1<(inputs.length-1);i1++) 
      { 

       for(int j=0;j<(inputs.length-1);i1++) 
       { 
        if(i1!=j) 
        { to_cmp=inputs[i1].toString(); 
         with_cmp=inputs[j]; 
         status=compare_entry(to_cmp,with_cmp); 
         if (status) 
         {counter++;} 
        } 
       } 

      } 
      System.out.println("The number of complementary strings are "+counter); 
     } 

} 

public static boolean compare_entry(String to_cmp,String with_cmp) 
{Boolean stat=false; 
for(int i=0;i<(to_cmp.length()-2);i++) 
{ 
    if(to_cmp.charAt(i)!=with_cmp.charAt(i)) 
    {stat=true; 
    } 
    else 
    { 
     break; 
    } 
} 
    return stat;} 
} 

但我正在逐漸陣列出鍵errorin線58即在此行中的 to_cmp =輸入[I1]的ToString();

+1

不應該爲循環是:'for(int j = 0; j <(inputs.length-1); - > j ++ < - )' – jlordo 2013-04-20 19:08:02

+0

有人只是複製/粘貼一些代碼而沒有審查它之前編譯它 – 2013-04-20 19:15:59

+0

luiggi門多薩不不公平。我自己寫了這個代碼 – 2013-04-20 19:45:12

回答

5

in for循環與j你再次遞增i1。 你有

for(int j=0;j<(inputs.length-1);i1++) 

這應該是

for(int j=0;j<(inputs.length-1);j++) 
+0

謝謝我只是急着寫,看不到 – 2013-04-20 19:48:05

1

的問題是在這條線:

for(int j=0;j<(inputs.length-1);i1++) 

修復這樣的:

for(int j=0;j<(inputs.length-1);j++) // it's j++, not i1++ 

你看,你正在增加錯誤的c ounter。此外,循環條件有點奇怪,通常我們使用i < inputs.length:請注意,我們不會從長度中減去1,否則將不會訪問數組中的最後一個元素。