2016-01-27 70 views
0

我正在從_(1-9)間隔的文件中讀取數據,然後用每個數字對堆棧進行一些操作。我只是試圖讓我的案例閱讀數組中的每個項目,併爲每個數字做些事情,但我似乎無法讓它工作。我無法讓我的堆棧工作

public static void main(String[] args) throws FileNotFoundException { 
    FileReader file = new FileReader("textfile.txt"); 
    int[] integers; 
    integers = new int[100]; 
    int i = 0; 
    try (Scanner input = new Scanner(file)) { 
     while (input.hasNext()) { 
      integers[i] = input.nextInt(); 
      i++; 
     } 

     Stack<Integer> nums = new Stack<>(); 
     int number = integers[i]; 
     switch (number) { 
      case '1': 
       nums.push(5); 
       System.out.println(nums.peek()); 
       break; 
     } 
    } catch (Exception e) { 
    } 
} 
+0

你的具體問題是什麼? –

回答

2

在你的switch語句,採取從數字1

'1'單引號出來的類型是char

1類型爲int

而且,當你嘗試在這裏得到一個數字:

int number = integers[i]; 

總是會是0,因爲i現在是一個比您在數組中實際填充的索引更大的索引。

+0

所以把它拿出來,讓它切換(整數[i]); ? – CorDell

+0

你想完成什麼?如果您只是想了解一下'Stack'和switch語句,請嘗試'switch(1)'。添加更多'case'語句,看看會發生什麼。 – Riaz

+0

從讀入的文件中讀取數字,然後用它們執行某個任務並將其等同於堆棧。 – CorDell