2014-09-19 56 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()); 

     } 
    } 


    }