Reading double values from a file

前端 未结 4 1162
夕颜
夕颜 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:33

    Below is my rendition of your code, adapted to make it run. It immediately explodes with an array indexing exceptions.

    So: Can you give us a little more framework? What's different from what I did?

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Zenzen {
    
       private static ArrayList tmp = new ArrayList();
    
       private static File file = new File("Zenzen.dat");
    
       public static void main(String[] args) {
    
          Scanner scan;
          try {
             scan = new Scanner(file);
             Object[][] tmp2 = new Object[tmp.size() / 2][2];
             int tmp3 = 0;
    
             while (scan.hasNextDouble()) {
                tmp.add(scan.nextDouble());
                System.out.println(Arrays.deepToString(tmp.toArray())); // debug print
                for (int i = 0; i < tmp.size() / 2; i++) {
                   for (int j = 0; j < 2; j++) {
                      tmp2[i][j] = tmp.get(tmp3);
                      tmp3++;
                   }
                }
             }
    
          } catch (FileNotFoundException fnfe) {
             fnfe.printStackTrace();
          }
       }
    }
    

    [0.0]
    [0.0, 0.0]
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at Zenzen.main(Zenzen.java:26)
    

提交回复
热议问题