java - 如何对栈中的元素求和

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

最佳答案

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

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

关于java - 如何对栈中的元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19487641/

相关文章:

c - 缓冲区溢出实验

C编程。指向结构的指针

python - 如何从 ExitStack 中删除上下文管理器

c# - 使用 ToArray() 将列表转换为数组

java - tomcat 9 中解析路径

java - java ArrayList中的元素占用两个位置

java - DataNucleus 3.0.0 版本需要哪些依赖项?

java - 当参数值为空时如何在@Cacheable中创建多个缓存键

java - 为 toArray 方法创建通用数组

javascript - 为什么当子项与 React.Children.toArray 一起使用时键会改变?