2016-11-30 71 views
0

实现将元素添加到类CacheMemory的方法。 类高速缓冲存储器有一个数组内存,其长度通过构造函数传递。元素只有在之前没有添加元素并且所添加数组的长度在数组边界内时才可以添加到元素中。其长度)。通过方法将字符串传递给数组

这是我想出了迄今为止代码:

public class CacheMemory { 

    private String[] memory; 

    public CacheMemory(int length) { 
     this.memory = new String[length]; 
    } 

    public void addingElementsToCache(String mem) { 
     for (int i = 0; i < memory.length; i++) { 
      if (memory[i] != mem) { 
       memory[i] = mem; 
       System.out.println(mem); 
       break; 
      } else { 
       System.out.println("Element already exists"); 
      } 
     } 
    } 
} 

如果我叫不打破这种方法,当然它会打印出字符串五次,但我不希望相同的字符串要打印出五次,我想添加五个不同的字符串,然后,while循环遍历数组,并且到达已经传递的元素,以打印出消息。

+0

'如果(记忆[I] != mem){'should be'if(memory [i] .equals(mem)){'因为您比较了字符串 – XtremeBaumer

+0

您正在使用'!='比较字符串。这不符合你的想法。改用'!memory [i] .equals(mem)'。 – Jesper

+6

请参阅:[如何比较Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839) – Jesper

回答

0

实际上,您需要使用!string.equals("anotherString")而不是!=,因为!=只比较字符串的地址,而不是字符串的内容,但方法等同于此。

0

你有一些逻辑错误。您必须等到您检查完缓存中的所有元素后才能确定它不存在。而且,你应该使用.equals()来比较字符串。

public void addingElementsToCache(String mem) 
{ 
    // Loop over slots 
    for (int i = 0; i < memory.length; i++) 
    { 
     if (memory[i] == null) { 
      // You have reached an unused slot, use it! 
      memory[i] = mem; 
      System.out.println(mem); 
      return; 
     } 
     else if (mem.equals(memory[i])) { 
      // You found a duplicate 
      System.out.println("Element already exists"); 
      return; 
     } 
    } 
    // You have checked all positions without finding an empty slot 
    System.out.print("The cache was full, unable to add!"); 
} 

如果用

public static void main(String[] args) 
{ 
    CacheMemory cache = new CacheMemory(10); 
    asList("foo", "foo", "bar", "boz", "bar") 
     .forEach(cache::addingElementsToCache); 
} 

行使该代码......它将打印以下,这是我想你想到:

foo 
Element already exists 
bar 
boz 
Element already exists 
+0

谢谢你,它的工作! 我已经通过构造函数传递了数组值,所以它按预期打印。 –

相关问题