从文件读取时为什么会出现java.lang.ArrayIndexOutOfBoundsException?

时间:2019-07-16 06:02:00

标签: java

给出:

包含file的125,000多个字典单词。

在命令行上提供了file进行拼写检查。

传递给构造函数的哈希乘数为31,存储桶值为4093。

我有两个程序应该从FileReader上的“ dictionary.txt”中读取fr = new FileReader(args [0]);我收到“ java.lang.ArrayIndexOutOfBoundsException:0”错误。如何解决该问题以获得正确的输出?

 import java.io.BufferedReader;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.Reader;
 import java.io.StreamTokenizer;



 public class Project6  
 { 
static StringHash obj;
 public static void main(String args[])
 { 
 obj=new StringHash();
  try
  {
  FileReader fr=new FileReader("dictionary.txt");
  BufferedReader br=new BufferedReader(fr);
  String word;


  while((word=br.readLine())!=null) 
  { 
    word=Project6.removeNonLetDig(word);
    obj.add(word); 
  }

  br.close();
  fr.close();

}catch(FileNotFoundException ex) 
{

  ex.printStackTrace();
}
catch(IOException ex)
{
  ex.printStackTrace();
}

try

{

  FileReader fr=new FileReader(args[0]);
  BufferedReader br=new BufferedReader(fr);
  String line;
  String word[];
  while((line=br.readLine())!=null)

  {

    word=line.split(" ");
    for(int i=0;i<word.length;i++)

    {

      if(!obj.hasWord(word[i]))

        System.out.println(word[i]);

    }

  }



}catch(FileNotFoundException ex)

{

  ex.printStackTrace();



}

catch(IOException ex)

{

  ex.printStackTrace();

}



}

 public static String removeNonLetDig(String s) 
 {

int b = 0, e = s.length()-1;




while (b <= e && !Character.isLetterOrDigit(s.charAt(b)))

  b++;




while (e >= b && !Character.isLetterOrDigit(s.charAt(e)))

  e--;

if (b <= e)

  return s.substring(b,e + 1);

else

  return null;

 }

}

//

class StringHash
{
class Node
{
String word;
Node next;
Node() 
{ 
  word="";
  next=null;
}
Node( String word,Node next)  
{    
  this.word=word;
  this.next=next;
}

public void setWord(String word)
{
  this.word=word; 
}

public void setNext(Node next) 
{
  this.next=next;
}

public String getWord() 
{
  return word;
}

public Node getNext()
{
  return next; 
}  
}

Node[] buckets;
private int BUCKETS;
private int MULT;

StringHash() 
{ 
MULT= 31;
BUCKETS=4093; 
buckets=new Node[BUCKETS]; 
for(int i=0;i<4093;i++)    
  buckets[i]=null;
}

public int hashValue(String s) 
 {
int h;  
int x, l = s.length();        
h = 0;

for ( x =0; x < l; x++ )     
  h = h * MULT + s.charAt(x);

if ( h < 0 )     
  h = -h;

return (h % BUCKETS);   
 } 

 public void add(String word)
 {
int hValue=hashValue(word);  
Node temp=buckets[hValue];
if(temp==null)

{ 
  temp=new Node(word,null);
  buckets[hValue]=temp;
}
else
{
  while(temp.next!=null)
  temp=temp.next;
  temp.next=new Node(word,null);
  }
}

public boolean hasWord(String word)    
{
int hValue=hashValue(word);  
Node temp=buckets[hValue];
while(temp!=null)     
{
  if(temp.word.equalsIgnoreCase(word)) 
    return true;
  temp=temp.next; 
}  
return false;    
  }
}

-



0 个答案:

没有答案