在for循环中保存值

时间:2014-11-20 22:18:55

标签: java loops for-loop save

所以我有以下代码

for (int i = 0; i <= numberOfTickets; i++) 
    {
        System.out.println("Please enter your age or if you are a student enter -1");
        int age = input.nextInt();

        if ((age < 10) && (age > 0)) 
        {
            cost = (cost / 4);
        } 
        else if ((age < 16) && (age >= 10)) 
        {
            cost = (cost / 2);
        } 
        else if (age > 60) 
        {
            cost = (cost / 2.5);
        }
        else if (age == -1)
        {
            cost = (cost / (4/3));
        }
        System.out.println(cost);
        }

问题是最初的成本是10英镑而用户输入12岁时我想要将£5的值保存为int int ticketCost1,然后再继续for循环,但再次从10开始。 从本质上讲,我希望在循环结束时可以获得所有折扣的费用,并且可以将所有折扣应用在一起,然后将它们全部合并在一起并支付最终费用。

P.S。我打算增加更多,以便每个孩子,即0至10岁,然后他们可以与16岁以上的任何人一起免费。

在java。

2 个答案:

答案 0 :(得分:0)

制作一个新的双,现在让我们称之为总和。现在而不是写作:

 cost = (cost/whatever);

这样做:

sum+= (cost/whatever);

现在你将它们全部保存在1个数字中,并且费用保持为10;虽然所有折扣都适用。只需确保将sum初始化为0 OUTSIDE且在for循环之前

答案 1 :(得分:0)

如果我理解正确,你就有一群年龄不同的人,你想找到该团购的所有门票的总费用。您可以有两个列表:一个用于存储年龄,另一个用于存储票证成本。该组的成本将是存储在第二个列表中的总成本。

static final TICKET_PRICE = 10;

int getTotalCost(List<Integer> ages) { // populated list of ages
    List<Integer> costs = new ArrayList<>();
    for (int i : ages)
        costs.add(getTicketPrice(int age));
    int totalCost = 0;
    for (int curr_cost : costs)
        totalCost += curr_cost;
    return totalCost;
}

int getTicketPrice(int age) {
    int price;
    if (age > 60) price = TICKET_PRICE/2.5;
    ... // all the other conditions, e.g. for students, children under 10, etc.
    else price = TICKET_PRICE; // if no special condition applies
    return price;
}

对于更复杂的条件(例如,10岁以下的孩子与16岁以上的其他人一起免费),最好是使用单独的方法来计算总费用。请记住,当您增加这些不仅取决于个人的条件,而且取决于整个群体的年龄分布时,最优成本计算本身就会开始变得非常复杂。