0

Here is my code

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

    }
}

Very new to java. Just need to know the SIMPLEST and EASIEST way to add all the values in the stack together. ie. If the stack was [1, 2, 3] the answer would be 6

1
  • 1
    you would need to add the logic in your if statement, what have you tried so far? Commented Feb 16, 2016 at 23:24

1 Answer 1

1

I would declare a variable named total and in your if(number== 0) statement:

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

You should also modify your print statement to print the value of total

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.