2014-09-19 89 views
0

我創建了一個雙精度數組列表,它應該存儲所有掃描程序檢測到的雙精度值的單元格。但是,當我運行代碼時,程序會一直詢問下一個輸入,我不知道爲什麼。ArrayList和scanner.hasNext遇到問題

例如,如果我的輸入是2,3,9,我希望程序將值2存儲到數組列表的第一個單元格,值3到第二個,值9到第三個。問題是,如果我在交互窗格中填寫2,3,9,它會一直詢問下一個輸入。

ArrayList<Double> doubleList; 
    doubleList = new ArrayList<Double>(); 

    while (scanner.hasNextDouble()) { 
     doubleList.add(scanner.nextDouble()); 
    } 
+0

是什麼讓它停下來?你只需要3個輸入? – 2014-09-19 21:16:49

+0

什麼是掃描儀的類型? – ChoChoPK 2014-09-19 21:20:04

+0

@ChoChoPK:'Scanner'是'Scanner'。沒有其他類型的綁定完成了。如果它來自文件或標準輸出,它也不會*真的很重要。 – Makoto 2014-09-19 21:20:36

回答

0
Is this what you want to do? Hope it helps. 

I have a test.txt file 
and it has 
2 
3 
4 
9 

running will give you output: 

[2.0] 
[2.0, 3.0] 
[2.0, 3.0, 4.0] 
[2.0, 3.0, 4.0, 9.0] 



    public class test2 { 

    public static void main(String[] args) throws FileNotFoundException 
    { 
    ArrayList<Double> doubleList; 
     doubleList = new ArrayList<Double>(); 
     File myFile = new File("C:\\test.txt"); 
     Scanner scanner = new Scanner(myFile); 

     while (scanner.hasNext()) { 
      if (scanner.hasNextDouble()) 
       doubleList.add(scanner.nextDouble()); 
      System.out.println(doubleList.toString()); 

     } 
    } 


    }