简体   繁体   中英

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

I don't know how to add all of the things in a stack together.

I already have:

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

This repeatedly printed 0's.

Stacks have both a push and a pop method. The push method pushes an object down onto the stack and the pop method pops the top object off the stack. Each call to push will increase the stack size by 1 and each pop will decrease the stack size by 1.

With a small modification to your code we can total up all the numbers that have been added to your stack.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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