Java- 数据结构堆栈:从用户输入的堆栈中打印出整数

Java- data structures stack: printing out integers from a stack from user input

我正在编写一个程序,允许用户在堆栈中输入一个正整数列表(以 0 结尾)并以相反的顺序显示它们。我首先尝试打印出堆栈的元素以先对其进行测试,但是当我输入 0 时程序没有打印出元素。 这是我的程序:

import java.util.*;
public class MyClass{

public static void main(String[] args) {

    Scanner sc= new Scanner(System.in);

    Stack<Integer> addToStack= new Stack<Integer>();

   int num;
   System.out.println("Enter the a list of positive integers. Terminate with a 0.");
   num= sc.nextInt();
   while(num!=0){

       addToStack.push(num);

   }
    System.out.println("Displaying numbers from the stack "+ addToStack);
  }
}        

你有一个无限循环。你必须重新向用户询问一个新的整数,否则你将无限期地循环

while(num!=0){
    addToStack.push(num);
    num= sc.nextInt();
}

您的代码将 运行 infinitely.You 必须在循环内写入 num= sc.nextInt();

例如:

while(num!=0){
    addToStack.push(num);
    num= sc.nextInt();
}

接受用户输入

您可以使用无限循环获取用户输入并在输入为 0 时中断循环。

正在对用户输入进行排序

当你需要对输入进行倒序排序时。所以你可以使用默认的 java 集合排序方法 Collections.sort(List,Compartor),它在 Collections class 中提供。

使用以下代码。

class MyClass {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Stack<Integer> addToStack = new Stack<Integer>();

        int num;
        do {
            System.out.print("Enter the a list of positive integers. Terminate with a 0.");
            num = sc.nextInt();
            addToStack.push(num);
        } while (num != 0);

        //sort reverse order 
        Collections.sort(addToStack, Collections.reverseOrder());

        System.out.print(addToStack);
    }
}

你没有在循环中控制你输入的号码。

用这些改变你的 while 条件 while ((num = sc.nextInt()) != 0) {

现在的结果是:

Enter the a list of positive integers. Terminate with a 0.
1
2
0
Displaying numbers from the stack [1, 2]