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的倍數,然後返回倍數之和。我發現了所有倍數。我有一個預感,我需要將堆棧轉換爲數組。如果是這樣,我會只使用stack.toArray()?那麼我會將它們添加到for循環中?如何彙總堆棧元素
你爲什麼要使用堆棧來保存倍數?你有沒有研究過使用其他數據結構? – SimonC
在當前的程序中,最多隻能有一個號碼。無需循環。 – Henry
我認爲最大的問題是,如果你只是試圖找到這些倍數的總和......你真的需要把它們放在堆棧中嗎?你會需要再次訪問這些數字嗎?爲什麼不呢,而不是將這些數字推入堆棧,只需開始將這些數字添加到一個int中,那麼您可以獲得totalSum? – aug