【发布时间】:2018-04-16 07:00:58
【问题描述】:
我这里有两节课:
public class Invoice {
ArrayList<Double> ItemPrices= new ArrayList<Double>();
ArrayList<Boolean> ItemIsPet = new ArrayList<Boolean>();
ArrayList<Integer> ItemQuantitys = new ArrayList<Integer>();
public void add(Item anItem){
}
public static void main(String args[]){
int counter = 0;
boolean pet;
Scanner s = new Scanner(System.in);
do {
System.out.println();
System.out.print("Item " + counter+1 + ":");
System.out.println();
System.out.print("Please enter the item's price: ");
double inputprice = s.nextDouble();
System.out.println();
System.out.print("Is this item a pet? (Y/N): ");
String inputIsPet = s.next();
if (inputIsPet.equals('Y')){
pet = true;
}
else {
pet = false;
}
System.out.println();
System.out.print("What is the quantity of this item?: ");
int inputquantity = s.nextInt();
Item newItem = new Item(inputprice, pet, inputquantity);
counter += 1;
} while (true);
}
}
这是第二类:
public class Item {
Invoice Inv = new Invoice();
public Item(double price, boolean isPet, int quantity){
}
}
我的问题是在这里:
Item newItem = new Item(inputprice, pet, inputquantity);
所以我从用户输入中获得了这 3 个必要的参数,这样我就可以创建一个类型为 item 的新对象 newItem,但我的问题是,一旦我有了对象 newItem,我该如何访问这些输入的参数?我的任务是迫使我实现这个特殊的“添加”方法:
public void add(Item anItem)
基本上,我想使用这种方法的方式是从这里获取输入的参数:
Item newItem = new Item(inputprice, pet, inputquantity);
并让“add”方法访问它们,然后将它们放入这些数组中:
ArrayList<Double> ItemPrices= new ArrayList<Double>();
ArrayList<Boolean> ItemIsPet = new ArrayList<Boolean>();
ArrayList<Integer> ItemQuantitys = new ArrayList<Integer>();
但是我如何访问对象newItem 的各个部分?我是否必须以某种方式修改我的构造函数?
【问题讨论】:
-
将实例字段和 getter 添加到 Item 类,一切顺利
-
这些数组是你作业的一部分吗?我猜不会,因为它们看起来非常笨重且不面向对象。
标签: java class constructor instance