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

时间:2015-09-28 12:48:08

标签: java stack

我正在编写一个程序,允许用户在堆栈中输入正整数列表(以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);
  }
}        

4 个答案:

答案 0 :(得分:2)

您无法循环控制输入的号码。

使用这些while ((num = sc.nextInt()) != 0) {

更改您的while条件

结果现在是:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

您的代码将无限运行。您必须在循环中编写num= sc.nextInt();

e.g:

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

答案 3 :(得分:1)

接受用户输入

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

对用户输入进行排序

当您需要按相反顺序对输入进行排序时。因此,您可以使用Collections.sort(List,Compartor)类中提供的默认java集合排序方法Collections

使用以下代码。

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);
    }
}
相关问题