如何在java(OOP)中为数组变量设置属性,在第43行为什么o[0].name不起作用?



如何在java(OOP(中为数组变量设置属性?o[]的属性无法在for循环中设置,为什么?我试图为 o[0] 设置名称,但 o[0].name 不起作用。为什么会这样?二传手和吸气手也不起作用,你能帮我解释为什么不能在 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);
}
}

您需要先初始化 o[i] 对象,然后再将其分配给其属性。
您的循环应该在达到数组长度之前终止,因为您从 ZERO 开始迭代器。您的 for 循环应如下所示:

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:");
}

最后要注意的是为您的变量提供有用的名称。当代码变大时,这是非常有用的,并且是程序员的良好做法。
希望代码片段有效!

相关内容

最新更新