java - 使用对象数组创建字典

标签 java arrays dictionary

我的这段代码有问题。我的目的是创建一个字典,使用对象数组(我不能使用 HashMap 或其他东西)来计算文本中单词的频率。我创建了一个类 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();}

}

以及使用 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;
  }
}

在我使用 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);
  }
}

但是它不起作用,特别是变量“count”没有增长。 例如,如果我写“你好吗”,我会得到:

how 1
are 1
you 1

有人可以帮我吗?

最佳答案

p.count++ 更改为 previous.count++

否则,您永远不会更改现有 Pair 的数量。

 Pair p=new Pair(s,1); 
 Pair previous=d.find(p);
 if(previous!=null) {         
     previous.count++;
 } else {
     d.insert(p);
 }

关于java - 使用对象数组创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469768/

相关文章:

python - 对映射中的键进行排序

java - ReSTLet,还活跃吗?

java - getColor 方法上的资源未找到异常

java - 比较二维数组

python - 循环中的唯一值数组

python - 用零或字符串替换字典值中的所有整数

c# - 为什么我不能在 C# 中定义不区分大小写的字典?

java - MapReduce 计数问题

java - 在 Spring 验证接受 header

arrays - 多维数组中的多重赋值