2013-04-20 50 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,否则将不会访问数组中的最后一个元素。