用户如何选择多张票,然后要求每张票的奖金总额?

时间:2017-11-03 23:28:51

标签: java

制作一个程序,询问1到5之间的票数。 然后我需要知道每张票的奖品,要求用户把它放好。 然后总计总和。

    //kb = keyboard, t = tickets, val = prize, sm = sum tickets
    Scanner kb = new Scanner(System.in);
    int t = 0;
    double val = 0,sm = 0;

    //this is a loop just for know the ticket number.
    do {
        System.out.print("How many tickets do you have?[max 5]");

        while(!kb.hasNextInt()){
            kb.nextLine();
            System.out.println("This is not valid, try again.");                
        }
        t = kb.nextInt();
    } while ((t <= 0 || t >= 6));

问题或我遇到的问题就在这里。(需要与之相关)

    //With the for I can ask for the value of each ticket
    for (int i = 1; i<=t ;i++) {
        System.out.println("Ticket número "+i+" es de:");
        val = kb.nextDouble();
    }

我如何总结每张票的不同奖金以赚取总金额?

2 个答案:

答案 0 :(得分:1)

for (int i = 1; i<=t ;i++) {
    System.out.println("Ticket número "+i+" es de:");
    val = kb.nextDouble();
    sm = sm + val;
}

答案 1 :(得分:1)

您可以完全删除val,只需直接添加到总和中:

for (int i = 1; i<=t ;i++) {
    System.out.println("Ticket número "+i+" es de:");
    sm += kb.nextDouble();
}