如何从单独的类中获取用户输入

时间:2019-05-08 04:53:16

标签: java

我的目标是获取一个项目的金额以及该项目的描述。我想获得10个输入及其值。我不知道如何在不要求一个然后另一个的情况下存储他们的信息。我希望能够要求用户输入项目,然后输入价格,然后存储每个值。

我试图创建一个要输入的对象数组,然后建议使用我理解但不知道在这种情况下如何实现的数组列表。

<script>

$(window).load(function () {
    $.getJSON('https://ipapi.co/json', function (result) {
        if (result.country == 'IN') {
//            var walk_in = localStorage.getItem('walk_in');
//            if (walk_in == null) {
//                localStorage.setItem('walk_in', 1);
                // Show popup here
                setTimeout(function(){
                $('#walkin').modal('show');
            },2000);
           // }
        }
    });
});
</script>
import java.util.ArrayList;

public class Invoice {
    private ArrayList<Item> listOfItems;

    public Invoice() {
        listOfItems = new ArrayList<Item>();
    }


    public void addItem(Item item) {
        listOfItems.add(item);
    }

    public double calculateNetItemCost() {
        double netCost = 0;
        for(Item currentItem : listOfItems) {
        netCost += currentItem.getCost();
        }

        return netCost;
    }

    public double calculateTax(double taxRateAsADecimal) {
        return calculateNetItemCost() * taxRateAsADecimal;
    }

    public double calculateGST() {
        double GST = calculateNetItemCost() * 0.05;
        return GST;
    }

    public double calculatePST() {
        double PST = calculateNetItemCost() * 0.07;
        return PST;
    }

    public double calculateTotalCost() {
        double total = calculateGST() + calculatePST() + calculateNetItemCost();
        return total;
    }

}

public class Item {
    private double amount;
    private String description;

    public Item(String description, double amount) {
        this.amount = amount;
        this.description = description;
    }

    public String toString() {
        return description + ", $" + String.format("%.2f", amount);
    }

    public double getCost() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

1 个答案:

答案 0 :(得分:0)

此代码段是您想要的。要求用户输入,然后使用值初始化对象

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter description(e.g.apple,banana,orange):");
    String description =input.nextLine();
    System.out.println("Please enter Price(e.g.4.0,5.99):");
    Double price = scanner.nextDouble();
    Item testItem = new Item(description, price);

用于循环:

for(int i =1;i<10;i++) {
        System.out.println("Please enter description(e.g.apple,banana,orange):");
        String description =input.nextLine();
        System.out.println("Please enter Price(e.g.4.0,5.99):");
        Double price = scanner.nextDouble();
testInvoice.addItem(new Item(description, price));
}