【发布时间】:2014-12-21 19:00:19
【问题描述】:
我想使用 Array Of Objects 创建一个索引。索引当然代表单词和包含该单词的行。我创建了一个名为 Pair 的类,它代表对 (word,lines) ,其中行包含在整数数组中。 类是
public class Pair
{ private String word;
private int [] a;
private int inputSize;
public Pair(String word,int line)
{this.word=word;
a=new int [10];
a[inputSize++]=line;
}
public String getWord()
{return word;}
public void addPosition(int line) //resize
{ if(inputSize==a.length-1)
{ int[] newA=new int [2*inputSize];
for(int i=0;i<inputSize;i++)
{ newA[i]=a[i];}
a=newA;
}
a[inputSize++]=line;
}
public String getPositions()
{String s="";
for(int i=0;i<inputSize;i++)
{s=s+" "+a[inputSize] ;}
return s;
}
public String toString()
{ String ss="";
ss=getWord()+" [ " +getPositions()+" ] ";
return ss;
}
}
在我创建类索引之后
public class Index
{ private Pair [] a;
private int inputSize;
public Index()
{a=new Pair [10];
inputSize=0;
}
public void add(String word,int pos)
{ if(inputSize==a.length-1)
{ Pair [] newA=new Pair [2*inputSize];
for(int i=0;i<inputSize;i++)
{ newA[i]=a[i];}
a=newA;
}
Pair p=new Pair(word,pos);
for(int i=0;i<inputSize;i++)
{ if(a[i].getWord().equals(word)) // i check if "word" is already in the array, if so i add the new line
{ a[i].addPosition(pos);
}
}
a[inputSize++]=p;
}
public String toString()
{String s="";
for(int i=0;i<inputSize;i++)
{ s=s+a[i].toString()+"\n";
}
return s;
}
}
在我创建了主类之后
import java.io.*;
import java.util.*;
public class IndixTester
{public static void main(String [] args)
{ FileReader read=null;
Index index=new Index();
Pair p;
try{read=new FileReader("input.txt");
}
catch(IOException e)
{System.err.println("errore");
}
int line=0;
Scanner c=new Scanner(read);
while(c.hasNextLine())
{ String s=c.nextLine();
line++;
Scanner token=new Scanner(s);
token.useDelimiter("[^A-Za-z0-9]+");
while(token.hasNext())
{
String ss=token.next();
index.add(ss,line);
}
token.close();
}
System.out.println(index.toString());
}
}
但它不起作用!我有这样的东西:
[0 0]
一个[0 0 0 0 0]
- 狗[0 0 0]
而不是像这样的东西
- [2 3]
- 一个 [12 4 3 5]
- 狗 [1 2]
当然,数字代表包含该单词的行。 请帮我。 非常感谢
【问题讨论】:
标签: java arrays dictionary