2010-04-09 61 views
0

我試圖做一個類,我把一個關鍵和值放入put方法,把k字符串數組中的鍵和值放入v字符串數組中,但它當我得到或顯示時沒有被保存在數組中。
例如:put(dan,30)get(dan)返回null
顯示返回null null 10次。有誰知道什麼是錯的?價值沒有被保存在字符串

public class Memory 
     { 
     final int INITIAL_CAPACITY = 10; 
     String[] k = new String[INITIAL_CAPACITY]; 
     String[] v = new String[INITIAL_CAPACITY]; 
     int count = 0; 

     public Memory() 
     { 
      count = 0; 
     } 
     public int size() 
     { 
      return count; 
     } 
     public void put(String key, String value) 
     { 
      int a = 0; 
      boolean found = false; 
      for (int i = 0; i < k.length; i++) 
      { 
       //System.out.println("key is " + key.equals(k[i])); 
       if (key.equalsIgnoreCase(k[i])) 
       { 
        v[i] = value; 
        found = true; 
       } 
       if (found) 
        break; 
       a++; 
      } 
      //System.out.println(a == k.length); 
      if (a == k.length); 
      { 
       k[count] = key; 
       v[count] = value; 
      //System.out.println(k[count] + " " + v[count]); 
       count++;   
      //System.out.println(count); 
      } 

     } 
     public String get(String key) 
     { 
      String output = "a"; 
      for(int i = 0; i < k.length; i++) 
      { 
      if(!key.equalsIgnoreCase(k[i])) 
      { 
       output = null; 
      } 
      else 
      { 
       output = v[i]; 
       return output; 
      } 
      } 
      return output; 
     } 
     public void clear() 
     { 
      for (int i = 0; i < k.length; i++) 
      { 
       k[i] = null; 
       v[i] = null; 
      } 
      count = 0; 
     } 

     public void display() 
     { 
      for (int i = 0; i < k.length; i++) 
      { 
       System.out.println(k[i] + " " + v[i]); 
      } 
     } 
    } 
+0

您是否試過單步執行代碼以查看它出錯的位置? – David 2010-04-09 23:05:34

+0

put方法不起作用,因爲陣列中沒有保存任何東西,並且count也沒有遞增 – Raptrex 2010-04-09 23:11:59

+0

您用來調用mehtods的代碼是什麼? – willvv 2010-04-09 23:13:50

回答

0

你的代碼適合我。

剛跑:

public static void main(String args[]){ 
     Memory newMem = new Memory(); 
     newMem.put("Dan", "30"); 
     System.out.println(newMem.get("Dan")); 
    } 

輸出功率爲 「30」

什麼是你的代碼看起來像創建/把/獲取?

+0

我將用戶類型放入dan 30或將dan放入命令行\t http: //pastie.org/912326 – Raptrex 2010-04-09 23:16:54

+0

我想通了,我創建了一個while循環內的對象,它不工作。 – Raptrex 2010-04-09 23:21:28

1

if (a == k.length);

分號去掉,否則它始終運行下面

塊,我希望這只是一個研究,因爲你應該只使用地圖,而不是實現一個自己。你的算法也很差。對於put和get都是O(n)表現。你實際上可以做得更好,比如O(log n)

+0

put方法中的for循環檢查key是否已經在數組中,如果是,它將更改您不明白的值 – Raptrex 2010-04-09 23:15:11

+1

。 'if(a == k.length);'這一行可以被刪除,你的代碼將完成同樣的事情。它是一個錯誤,因爲如果你把一個現有的鍵放在一起並且匹配,你還會將它添加到數組的末尾並增加計數。那麼你將有兩個具有相同值的鍵。 – Pyrolistical 2010-04-09 23:20:19

+0

在同一行上,如果鍵已經在數組中,則可以刪除'found'變量並跳出循環 – pgmura 2010-04-09 23:24:56

0
while(true) 
{ 
    Scanner kb = new Scanner(System.in); 
    Memory m = new Memory(); 
... 

每次循環時,都會創建一個新的Memory對象,而不是更新對現有對象的引用。