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

问题描述:

我正在编写一个程序,允许用户在堆栈中输入正整数(以0结尾)并按相反顺序显示它们。我第一次尝试打印出栈的元素来测试它第一,但该计划不打印出来的元素,当我输入0 这里是我的程序:Java-数据结构堆栈:从用户输入的堆栈打印出整数

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); 
    } 
}   
+1

'NUM = sc.nextInt();'应该在侧循环。 – Satya

以用户输入

可以使用无限循环采取用户输入和中断环路当输入是0

排序的用户输入

当您需要根据相反的顺序。因此,您可以使用Collections类中提供的默认Java收集排序方法Collections.sort(List,Compartor)

使用以下代码。

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); 
    } 
} 
+0

谢谢!但我想我将不得不使用pop(),因为我真的不被允许使用Collections类的方法,这种方法可以作为快捷键 – Tia

+0

您是否需要使用排序算法实现自定义排序方法? –

+0

通常情况下,你向他展示的问题不是他的作业:) –

你有一个无限循环。你不得不重新寻求新的整数用户,否则你将保持indefinetily

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

谢谢!好解释 – Tia

循环您的代码将运行infinitely.You有写num= sc.nextInt();内循环。

例如:

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

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

更改与这些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]