【问题标题】:Java- Using a constructor to place in values for a method?Java-使用构造函数为方法放置值?
【发布时间】: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


【解决方案1】:

我必须以某种方式修改我的构造函数吗?

是的,您需要将传入的值保存到实例字段中。

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;
    }

}

如何访问那些输入的参数?

然后你可以为你想要访问的每个字段编写一个getter。

public double getPrice() {
    return price;
}

如何访问对象newItem 的各个部分?

现在你可以了。

double price = newItem.getPrice();

【讨论】:

  • @MatthewButner,如果有帮助,您可以接受答案
猜你喜欢
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 2020-11-07
  • 2013-10-21
  • 2013-10-04
  • 1970-01-01
相关资源
最近更新 更多