2013-12-04 2 views
0

Мне нужна помощь в написании функций печати в этом приложении Java другого класса.Функции печати на Java

Функции с печатью. Я думаю, что это правильно, а другая функция определенно неверна.

public void printAll() { 
    Iterator<StockItem> iterator = values(); 
    while (iterator.hasNext()) 
     System.out.println(iterator.next().toString()); 
} 

// Prints a directory of all StockItems from the given vendor, 
// in sorted order (ordered by SKU). 
public void print(String vendor) { 
    Iterator<StockItem> iterator = values(); 
    if (dictionary.getItem(SKU).getVendor() == vendor) 
     System.out.println(tmp.toString()); 
} 

Вся функция, которую я опишу ниже для деталей, которые необходимы для этой проблемы.

import data_structures.*; 
import java.util.Iterator; 

public class ProductLookup { 


DictionaryADT<String,StockItem> dictionary; 
private int maxSize; 

public ProductLookup(int maxSize, DictionaryADT<String,StockItem> dictionary) { 
    this(maxSize); 
    this.dictionary = dictionary; 
} 

// Constructor. There is no argument-less constructor, or default size 
public ProductLookup(int maxSize) { 
    this.maxSize = maxSize; 
} 

// Adds a new StockItem to the dictionary 
public void addItem(String SKU, StockItem item) { 
    dictionary.insert(SKU,item); 
} 

// Returns the StockItem associated with the given SKU, if it is 
// in the ProductLookup, null if it is not. 
public StockItem getItem(String SKU) { 
    if (SKU == null) 
     return null; 
    return dictionary.getValue(SKU); 
} 

// Returns the retail price associated with the given SKU value. 
// -.01 if the item is not in the dictionary 
public float getRetail(String SKU) { 
    if (!dictionary.contains(SKU)) 
     return (float) -.01; 
    return getItem(SKU).getRetail(); 
} 

public float getCost(String SKU) { 
    if (!dictionary.contains(SKU)) 
     return (float) -.01; 
    return getItem(SKU).getCost(); 
} 

// Returns the description of the item, null if not in the dictionary. 
public String getDescription(String SKU) { 
    if (!dictionary.contains(SKU)) 
     return null; 
    return getItem(SKU).getDescription(); 
} 

// Deletes the StockItem associated with the SKU if it is 
// in the ProductLookup. Returns true if it was found and 
// deleted, otherwise false. 
public boolean deleteItem(String SKU) { 
    if (SKU == null) 
     return false; 
    return dictionary.remove(SKU); 
} 

// Prints a directory of all StockItems with their associated 
// price, in sorted order (ordered by SKU). 
public void printAll() { 
    Iterator<StockItem> iterator = values(); 
    while (iterator.hasNext()) 
     System.out.println(iterator.next().toString()); 
} 

// Prints a directory of all StockItems from the given vendor, 
// in sorted order (ordered by SKU). 
public void print(String vendor) { 
    Iterator<StockItem> iterator = values(); 
    if (dictionary.getItem(SKU).getVendor() == vendor) 
     System.out.println(tmp.toString()); 
} 

// An iterator of the SKU keys. 
public Iterator<String> keys() { 
    return dictionary.keys(); 
} 

// An iterator of the StockItem values.  
public Iterator<StockItem> values() { 
    return dictionary.values(); 
} 
} 

Поскольку это сбивало с толку, фактически не видя DictionaryADT, я включу его здесь.

package data_structures; 

import java.util.Iterator; 
import java.util.NoSuchElementException; 


public interface DictionaryADT<K,V> { 

// Returns true if the dictionary has an object identified by 
// key in it, otherwise false. 
public boolean contains(K key); 

// Adds the given key/value pair to the dictionary. Returns 
// false if the dictionary is full, or if the key is a duplicate. 
// Returns true if addition succeeded. 
public boolean insert(K key, V value); 

// Deletes the key/value pair identified by the key parameter. 
// Returns true if the key/value pair was found and removed, 
// otherwise false. 
public boolean remove(K key); 

// Returns the value associated with the parameter key. Returns 
// null if the key is not found or the dictionary is empty. 
public V getValue(K key); 

// Returns the key associated with the parameter value. Returns 
// null if the value is not found in the dictionary. If more 
// than one key exists that matches the given value, returns the 
// first one found. 
public K getKey(V value); 

// Returns the number of key/value pairs currently stored 
// in the dictionary 
public int size(); 

// Returns true if the dictionary is at max capacity 
public boolean isFull(); 

// Returns true if the dictionary is empty 
public boolean isEmpty(); 

// Returns the Dictionary object to an empty state. 
public void clear(); 

// Returns an Iterator of the keys in the dictionary, in ascending 
// sorted order. The iterator must be fail-fast. 
public Iterator<K> keys(); 

// Returns an Iterator of the values in the dictionary. The 
// order of the values must match the order of the keys. 
// The iterator must be fail-fast. 
public Iterator<V> values(); 
} 
+0

Что это за новый метод keys() и null в методе values ​​()(). – Bennet

+0

Те не написаны, из-за меня, не зная, что там положить – FlameArc

+0

Что такое DictionaryADT? Это ваш собственный класс, который имеет некоторый список внутри для хранения значений. – Bennet

ответ

0

Если DictionaryADT класс со всей фактической реализацией, то вам нужно позвонить

Я считаю, что у вас есть карта внутри DictionaryADT то, что-то вроде

public Collection<StockItem> values() { 
    return dictionary.values(); 
} 

, чтобы получить ключи, итератор изменяется до

public Set<String> keys() { 
    return dictionary.keySet(); // return Set, Please perform all the set opetations. 
} 

Я считаю, это то, что вы ищете.

Thanks, Bennet.

+0

Я думаю, что исправляет мой итератор, поэтому я отредактирую свои итераторы в исходном сообщении, и вы могли бы помочь мне с функцией печати. ​​ – FlameArc

+0

Вы создали интерфейс, но где вы храните свой объект. Вам нужно какое-то место для хранения ваших данных. Например, «Карта», «Список» или «Очередь». Или вам нужно реализовать свою собственную логику для хранения и извлечения данных. Для вашего понимания: предположим, что вы используете DictionaryADT.insert («Key», новый StockItem()) ;, где это значение сохраняется в JVM. Вы только объявили только интерфейс. – Bennet

0

Ни один из этих методов имеет никакого смысла:

// An iterator of the SKU keys. 
public Iterator<String> keys() { 
    return new ; 
} 

// An iterator of the StockItem values.  
public Iterator<StockItem> values() { 
    return null; 
} 

Первый не будет компилировать, а второй мгновенно вызывает неработающими при вызове. Теперь, что такое DictionaryADT? Использует ли он Map? Если это так, у него есть метод keySet и valueSet, который вы должны использовать. Возможно, вы можете заменить его на HashMap.

Вам не нужны toString звонки в print и printAll, хотя я предпочел бы, чтобы зарезервировать toString для отладки и написать отдельный метод. Однако, почему вы не можете использовать цикл Еогеасп, предполагая DictionaryADT орудия Map:

public void printAll() { 
    for (final StockItem item: dictionary.valueSet()) { 
     System.out.println(item); 
    } 
} 

Наконец, использовать equals вместо == в методе print. Вы можете посмотреть, почему.

+0

Да, я знаю об итераторах, оглядываясь назад, я должен был оставить их пустыми, чтобы вы никого не смутили. DisctionaryADT не реализует карту. Он реализован в различных функциях, таких как Hastable и BST. – FlameArc

Смежные вопросы