how to set attributes for array variable in java(OOP), in line 43 why o[0].name doesnt work? -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
how set attributes array variable in java(oop)? attributes of o[] not set within loop, why? im trying set name o[0], o[0].name doesnt work. why happened? setter , getter doesnt work either, can me explain why can not set attributes in o[]?
import java.util.scanner; public class orders { private string name; private double price; private int quantity; public void setname(string name){ this.name= name; } public string getname(){ return name; } public void setprice(double price){ this.price=price; } public double getprice(){ return price; } public int getquantity(){ return quantity; } public void setquantity(int quantity){ this.quantity=quantity; } public static void main(string[] args) { int num = 0; double sum=0; scanner sc = new scanner(system.in); system.out.println("how many rows of order: "); num = sc.nextint(); orders[] o = new orders[num]; sc.nextline(); for(int = 0;i<=o.length;i++){ system.out.println("the name of product: "); o[0].name=sc.nextline(); o[i].setname(sc.nextline()); system.out.println("price of product: "); o[i].setprice(sc.nextdouble()); system.out.println("quantity of product: "); o[i].setquantity(sc.nextint()); } for(orders a: o){ system.out.println("name: "+a.getname()+". price: "+a.getprice() +". quantity :"+a.getquantity()); double totalprice= a.getquantity()*a.getprice(); sum = sum + totalprice; } system.out.println("total price: "+sum); } }
you need initialize o[i] object before assigning attributes.
loop should terminate before reaching length of array since start iterator form zero. loop should this:
for(int = 0;i<o.length;i++){ o[i] = new orders(); system.out.println("the name of product: "); string name = sc.nextline(); o[i].setname(name); system.out.println("price of product: "); double price = sc.nextdouble(); o[i].setprice(price); system.out.println("quantity of product: "); int quantity = sc.nextint(); o[i].setquantity(quantity); sc.nextline(); system.out.println("moveing next order:"); }
one more final note have useful names varaibles. extremely helpful when code gets bigger , practice have programmer.
hope code snippet works!
Comments
Post a Comment