簡體   English   中英

使用對象數組創建字典

[英]Create a Dictionary using Array of Object

我對此代碼有疑問。 我的目的是使用對象數組(我不能使用哈希映射或其他方法)創建一個字典來計算文本中單詞的出現頻率。 我創建了一個包含配對(單詞,計數)的類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);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM