How to sum elements of a stack

2019-08-20 02:35发布

问题:

import java.util.*;

public class multiple {
    public static int userNumber;
    public static int userChoice;
    static Stack<Object> stack = new Stack<Object>();
    static int[] list = new int[100];

    public static void main(String[] args) {
        introduction();
        multiple();
        printStack(stack);

    }

    public static void introduction() {
        Scanner input = new Scanner(System.in);

        System.out.print("Welcome to the program, please enter the number  less than 100 that you would like "
                        + "to find whoes number \nbelow have muliples of 3 and 5: ");
        userNumber = input.nextInt();

        System.out.println();

        // System.out.println("Ok, now that youve entered," + userNumber +
        // " we will find out which numbers of you number are three and five. "
        // +
        // "would you like the result published as a:\n 1.alist \n 2.A sum of the result \n 3.Or both?");
        // userChoice = input.nextInt();

        // if (userChoice >=1 && userChoice <=3)
        // System.out.println( "The Computer will now program for" +
        // userChoice);

        // else
        // System.out.println("incorrect entry for menu. Please try again");

    }

    public static void multiple() {
        for (int i = 1; i < userNumber; i++) {
            if (i % 3 == 0 || i % 5 == 0) {
                stack.push(i);
            }
        }

    }

    // public static addElementsofstac

    private static void printStack(Stack<Object> s) {
        if (s.isEmpty())
            System.out.println("You have nothing in your stack");
        else
            System.out.println(s);
    }

}

I am trying to make a simple program that will take input for a user, find out the multiples of 3 & 5, then return the sum of the multiple. I have all the multiples discovered. I have a hunch that i need to convert the stack to an array. if so, would i just use stack.toArray()? then i would add them in a for loop?

回答1:

Alternative without the need for intermediary counter variable:

int sum = 0;
while (stack.size() > 0) sum += stack.pop();


回答2:

Why would you need an array?

You just need to do something along the lines of:

int sum = 0;
for(i=0;i<stack.size();i++){
    sum = sum + stack.pop();
}

Though I agree with the others in that there's really no purpose of the stack itself.

EDIT: your clarification is only more confusing. How are 3, 6 and 9 multiples of 10? Are you talking about integers less than an inputted number that are multiples of 3 and 5?