我想创建一个对象数组并在不同的函数中使用它。我写了这个伪代码
privat stock[] d;
privat stock example;
public void StockCheck(){
d =new stock[2];
d[0]= new stock("a","test1", 22);
d[1]= new stock("b","test2", 34);
}
@Override
public stock getStock(String name) throws StockCheckNotFoundException{
int i;
System.out.println("ok" + name + d.legth); // error
example = new stock("example","example",2);
return example;
}
在课堂测试中,我创建一个getStock实例,然后调用函数getStock stock.getStock();
当我执行d.length时,我得到一个NullPointerExeption。 d为空,但我不明白为什么。
答案 0 :(得分:1)
Hmmmm。如果这与您的真实代码有任何关系,那么问题是您的“构造函数”实际上不是构造函数,因为您已声明它返回void,而是使其成为普通方法。删除tbat“void”,它可以解决问题!
答案 1 :(得分:-1)
也许这个代码示例将使用三个类
来完成您的需要(注意:您可能真的想在StockQuote中使用ArrayList,以便添加和删除股票。)
测试类
package stackJavaExample;
public class Test {
public static void main(String[] args) {
String[] testNames = {"test1","test2","notThere"};
StockCheck mStockCheck = new StockCheck();
for (int i=0; i<testNames.length; i++) {
Stock result = mStockCheck.getStock(testNames[i]);
if (result == null) {
System.out.println("No stock for name: " + testNames[i]);
} else {
System.out.println("Found stock: " + result.getName() + ", " + result.getSymbol() + ", " + result.getValue());
}
}
}
}
库存类
package stackJavaExample;
public class Stock {
private String symbol;
private String name;
private double value;
public Stock(String symbol, String name, double value) {
this.symbol = symbol;
this.name = name;
this.value = value;
}
public String getSymbol() { return symbol;}
public String getName() { return name;}
public double getValue() {return value;}
}
StockCheck类
package stackJavaExample;
public class StockCheck {
private Stock[] d;
public StockCheck() {
d = new Stock[2];
d[0] = new Stock("a","test1", 22);
d[1] = new Stock("b","test2", 34);
}
public Stock getStock(String name) {
for (int i=0; i < d.length; i++) {
if (d[i].getName().equalsIgnoreCase(name)) {
return d[i];
}
}
return null;
}
}