0
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 循环中吗?

4

2 回答 2

2

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

int sum = 0;
while (stack.size() > 0) sum += stack.pop();
于 2017-11-30T01:30:33.333 回答
0

为什么需要数组?

你只需要按照以下方式做一些事情:

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

虽然我同意其他人的观点,堆栈本身实际上没有任何目的。

编辑:您的澄清只会更加混乱。10的3、6和9的倍数是多少?您是在谈论小于 3 和 5 倍数的输入数字的整数吗?

于 2013-10-21T12:40:58.367 回答