J. Doe J. Doe - 2 months ago 8
Java Question

how to set attributes for array variable in java(OOP), in line 43 why o[0].name doesnt work?

how to set attributes for array variable in java(OOP)? Inside the for loop why i cannot set name for o[]? Im trying to set name for o[0], but o[0].name doesnt work inside the for loop? why this happened? Also setter and getter also doesnt work for o[], 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);
}


}

Answer Source

You need to initialize your o[i] object before assigning it to its attributes.
Your loop should terminate before reaching the length of the array since you start your iterator form ZERO. Your for loop should look like this:

for(int i = 0;i<o.length;i++){
        o[i] = new Orders();
        System.out.println("The name of the 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 to the next Order:");
    }

One more final note is to have useful names for your varaibles. This is extremely helpful when the code gets bigger and a good practice to have as a programmer.
Hope the code snippet works!