2015-09-28 137 views
0

我正在編寫一個程序,允許用戶在堆棧中輸入正整數(以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

回答

1

以用戶輸入

可以使用無限循環採取用戶輸入和中斷環路當輸入是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

通常情況下,你向他展示的問題不是他的作業:) –

1

你有一個無限循環。你不得不重新尋求新的整數用戶,否則你將保持indefinetily

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

謝謝!好解釋 – Tia

1

循環您的代碼將運行infinitely.You有寫num= sc.nextInt();內循環。

例如:

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

您無法控制您在循環中輸入的號碼。

更改與這些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]