how to set attributes for array variable in java(OOP)? attributes of o[] could not be set within the for loop, why? Im trying to set name for o[0], but o[0].name doesnt work. why this happened? Also setter and getter doesnt work either, can you help 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 i = 0;i<=o.length;i++){
System.out.println("The name of the 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);
}
}