我得到了這個練習: 實現下面的類,它加載並打印一組數據值。我得到了空指針異常,因爲hashmap沒有被填充或者可能不是
import java.util.Iterator;
public class MyLoader {
public void loadAndPrintValues(Iterator<String> keysToLoad, Data data, Printer printer) {
// Load data values like this:
// String value = data.loadValue(key);
// Print loaded data value like this:
// printer.printEntry(key, value);
}
}
然而,當我做了練習,我得到了NullPointerException
,大概是從while (keysToLoad.hasNext())
或從key = keysToLoad.next();
。我想我得到了例外,因爲「數據」沒有得到充分的,但我不知道如何去做。這裏是我的代碼和錯誤消息
public interface Data{
//I made this method
public void makeEntry(String key, String value);
//given
public String loadValue(String key);
}
public interface Printer {
public void displayEntry(String key, String value);
}
import java.util.Iterator;
import java.util.HashMap;
public class MyLoader implements Data, Printer {
Data data; // = new MyLoader();
Printer printer; // = new MyLoader();
Iterator<String> iter; // = new MyLoader();
String key = "";
String value = "";
HashMap<String, String> ht = new HashMap<String, String>();
public MyLoader(){
// this.database = null;
// this.key = null;
// this.value = null;
// this.ht = null;
// this.iter = null;
System.out.println("now in the constructor");
}
public MyLoader(Iterator<String> iter, Data data, Printer printer){
this.data = data;
this.printer = printer;
this.iter = iter;
}
public void loadAndPrintValues(Iterator<String> keysToLoad, Data data, Printer printer) {
try {
if (ht.isEmpty()){
System.out.println("ht is empty");
throw new NullPointerException("Database is empty.");
}else {
this.data = data;
}
while (keysToLoad.hasNext()){
// Load data values like this:
key = keysToLoad.next();
value = data.loadValue(key);
// Print loaded data value like this:
printer.printEntry(key, value);
}
}catch (NullPointerException npe){
System.out.println("caught null pointer ");
System.out.println(npe.getMessage());
}
}
@Override
public void makeEntry(String key, String value){
ht.put(key, value);
}
@Override
public void printEntry(String key, String value) {
System.out.println("[" + key + " : " + value + "]");
}
@Override
public String loadValue(String key) {
System.out.println("loadValue:" + key);
if(this.ht.containsKey(key))
return this.ht.get(key);
else {
System.out.println("No key in database.");
throw new NullPointerException("No key in data.");
}
}
}
public class test {
public static void main(String[] args) {
try {
MyLoader mdbl = new MyLoader();
mdbl.makeEntry("0", "zero");
mdbl.makeEntry("1", "One");
mdbl.makeEntry("2", "Two");
mdbl.makeEntry("3", "Three");
mdbl.loadAndPrintValues(mdbl.iter, mdbl.data, mdbl.printer);
}
catch(NullPointerException e){
System.out.println(e.getMessage());
}
}
}
「*我得到了一個NullPointerException,可能來自... *」您的堆棧跟蹤會完全告訴您*發生異常的行。請發佈您的堆棧跟蹤。 – 2013-03-07 08:46:33
你可以發佈你的空指針堆棧跟蹤嗎? – 2013-03-07 08:46:42
練習是爲了理解,讓你學習語言。你需要學習調試。你在這裏得到的答案,但調試它會幫助你,而不是 – 2013-03-07 08:55:10