arrays - make a global object in java -
i want make array of objects , use in different functions. wrote pseudocode
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; }
in class test make instance of getstock , call function getstock stock.getstock();
i nullpointerexeption when d.length. d null don't understand why.
perhaps example of code need, using 3 classes
- test - main test code
- stock - implied code stock question
- stockcheck - corrected code question.
(note: may want use arraylist inside stockquote can add , delete stocks.)
test class
package stackjavaexample; public class test { public static void main(string[] args) { string[] testnames = {"test1","test2","notthere"}; stockcheck mstockcheck = new stockcheck(); (int i=0; i<testnames.length; i++) { stock result = mstockcheck.getstock(testnames[i]); if (result == null) { system.out.println("no stock name: " + testnames[i]); } else { system.out.println("found stock: " + result.getname() + ", " + result.getsymbol() + ", " + result.getvalue()); } } } }
stock class
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 class
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) { (int i=0; < d.length; i++) { if (d[i].getname().equalsignorecase(name)) { return d[i]; } } return null; } }
Comments
Post a Comment