简单的Java堆栈添加

时间:2016-02-16 23:16:50

标签: java stack

这是我的代码

package practice;

import java.util.Stack;

public class prac {
    public static void main (String[]args){
        int K = -1;
        do{
            System.out.print("Enter the amount of positive numbers to add up: ");
            K = In.getInt();
        } while(K<0);
        int i;
        Stack sum = new Stack();
        int number;
        int totalsum;
        System.out.println("Enter " + K + " values between 1 and 100, or a 0 to to ignore the last number submitted");
        for(i = 1; i <= K; i++){
            number = In.getInt();
            if(number == 0)
                sum.pop();
            else
            sum.push(number);

            System.out.print(sum);
        }

    }
}

非常新的java。只需要知道SIMPLEST和EASIEST方法就可以将堆栈中的所有值一起添加。即。如果堆栈是[1,2,3],答案将是6

1 个答案:

答案 0 :(得分:1)

我会声明一个名为total的变量 在你的if(number== 0)陈述中:

while(!sum.isEmpty()){
  total += sum.pop();
}

您还应修改print语句以打印total

的值