如何对堆栈的元素求和 [英] How to sum elements of a stack

查看:18
本文介绍了如何对堆栈的元素求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 & 的倍数.5,然后返回倍数之和.我发现了所有的倍数.我有一种预感,需要将堆栈转换为数组.如果是这样,我会只使用 stack.toArray() 吗?然后我会将它们添加到 for 循环中?

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?

推荐答案

无需中介计数器变量的替代方案:

Alternative without the need for intermediary counter variable:

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

这篇关于如何对堆栈的元素求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆