Reading double values from a file

前端 未结 4 1155
夕颜
夕颜 2020-12-20 23:51

I\'m trying to read some numbers (double) from a file and store them in an ArrayList and an array (yes, I need both) with the code below:

try {
    Scanner s         


        
4条回答
  •  暖寄归人
    2020-12-21 00:27

    I tried reducing the code down to only test the Scanner by itself. The following code works with your data file:

    public static void main(String[] args) {
        Scanner scan;
        File file = new File("resources\\scannertester\\data.txt");
        try {
            scan = new Scanner(file);
    
            while(scan.hasNextDouble())
            {
                System.out.println( scan.nextDouble() );
            }
    
        } catch (FileNotFoundException e1) {
                e1.printStackTrace();
        }
    
    }
    

    I got the following (expected) output:

    0.0
    0.0
    0.023
    0.023
    0.05
    0.05
    0.2
    0.2
    0.5
    0.5
    0.8
    0.8
    0.95
    0.95
    0.977
    0.977
    1.0
    1.0
    

    Try this to make sure you're referencing the correct file.

提交回复
热议问题