[英]Create a Dictionary using Array of Object
I have a problem with this code. 我对此代码有疑问。 My purpose is to create a Dictionary that counts the frequency of a word in a text, using an Array of Objects (I can't use Hash Map or something else).
我的目的是使用对象数组(我不能使用哈希映射或其他方法)创建一个字典来计算文本中单词的出现频率。 I created a class Pair that contains the couple (word,count).
我创建了一个包含配对(单词,计数)的类Pair。
public class Pair
{ public String word;
public int count;
public Pair(String word,int count)
{this.word=word;
this.count=count;
}
public String getWord()
{return word;}
public int getCount()
{return count;}
public void addCount()
{count++;}
public String toString()
{ return getWord()+" "+getCount();}
}
And the class Dict that creates an Array of object using the Pair class 以及使用Pair类创建对象数组的Dict类
public class Dict
{ private Pair [] a;
private int inputSize;
public Dict()
{a=new Pair[10];
inputSize=0;
}
public void insert(Pair x)
{ if(a.length==inputSize)
{ Pair newA []=new Pair [2*inputSize];
for(int i=0;i<inputSize;i++)
{ newA[i]=a[i];
}
a=newA;
}
for(int i=0;i<inputSize;i++) // i check if x is already in the array if i find it i replace it otherwise i add it in the array
{ if(a[i].getWord().equals(x.getWord()))
{a[i]=x;
}
}
a[inputSize++]=x;
}
public Pair find(Pair x) // if i don't find x return null
{ for(int i=0;i<inputSize;i++)
{ if(a[i].getWord().equals(x.getWord()))
{return a[i];}
}
return null;
}
public String toString()
{String s="";
for(int i=0;i<inputSize;i++)
{ s=s+a[i].toString()+'\n';
}
return s;
}
}
After I created the test class with the main method 用main方法创建测试类之后
import java.util.*;
import java.io.*;
public class MyDict
{public static void main(String [] args)
{ Dict d=new Dict();
Scanner c=new Scanner(System.in);
while(c.hasNext())
{String s=c.next();
Pair p=new Pair(s,1); // create a new pair
Pair previous=d.find(p);
if(previous!=null) //if the pair is already in the stack i add 1 to the counter otherwise i insert it in the array
{p.count++;}
else
{d.insert(p);}
s="";
}
System.out.println(d);
}
}
But it doesn't work, in particular the variable "count" doesn't grow. 但这是行不通的,特别是变量“ count”不会增长。 For example, if I write "how how are are you you " I get:
例如,如果我写“你好吗”,我会得到:
how 1
are 1
you 1
Can anyone help me please? 谁能帮我吗?
Change p.count++
to previous.count++
. 将
p.count++
更改为previous.count++
。
Otherwise you never change the count of the existing Pair
s. 否则,您永远不会更改现有
Pair
的计数。
Pair p=new Pair(s,1);
Pair previous=d.find(p);
if(previous!=null) {
previous.count++;
} else {
d.insert(p);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.