如何对堆栈的元素求和

时间:2013-10-21 06:32:12

标签: java stack toarray

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

}

我正在尝试创建一个简单的程序,为用户提供输入,找出3&amp;的倍数。 5,然后返回多个的总和。我发现了所有的倍数。我有一种预感,我需要将堆栈转换为数组。如果是这样,我会使用stack.toArray()吗?然后我会将它们添加到for循环中?

2 个答案:

答案 0 :(得分:1)

替代方案,无需中间计数器变量:

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

答案 1 :(得分:0)

为什么需要阵列?

你只需要按照以下方式做点什么:

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

虽然我同意其他人的意见,但堆栈本身并没有真正的目的。

编辑:您的澄清只会更令人困惑。 10,6的3倍,6倍和9倍如何?你是在谈论小于输入数字的整数是3和5的倍数吗?