繁体   English   中英

如何将堆叠中的所有数字一起添加,然后打印总数?

[英]How can I add all of the numbers in a stack together and then print the total?

我不知道如何将堆叠中的所有东西加在一起。

我已经有了:

  Stack <Integer> stack = new Stack <Integer>();
  stack.push(15);
  stack.push(30);
  int total = 0;
  while (!stack.isEmpty()) {
     print(total);
  }

这反复打印0。

堆栈同时具有pushpop方法。 push方法将对象向下推到堆栈上, pop方法将顶层对象弹出堆栈。 每次调用push都会将堆栈大小增加1,每次弹出都会使堆栈大小减少1。

通过对代码进行少量修改,我们可以累计已添加到堆栈中的所有数字。

 import java.util.Stack;

 Stack <Integer> stack = new Stack <Integer>();
  stack.push(15);
  stack.push(30);
  int total = 0;
  while (!stack.isEmpty()) {
    total += stack.pop();
  }
  print(total);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM