我这里有两个类(class):
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
,我如何访问这些输入的参数?我的任务迫使我实现这个特定的“add”方法:
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
的各个部分?我是否必须以某种方式修改我的构造函数?
最佳答案
Do I have to modify my constructor in some way?
是的,您需要将传入值保存到实例字段中。
public class Item {
private final double price;
private final boolean isPet;
private final int quantity;
public Item(double price, boolean isPet, int quantity) {
this.price = price;
this.isPet = isPet;
this.quantity = quantity;
}
}
How can I access those inputted arguments?
然后你可以为每个你想要访问的字段编写一个getter。
public double getPrice() {
return price;
}
How do I access the parts of the object
newItem
?
现在你可以了。
double price = newItem.getPrice();
关于Java-使用构造函数来放置方法的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49851286/