有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从文本文件中获取2D数组

我正试图从文本文件中获取2D数组。到目前为止,我访问了该文件并获得了文件中的所有数字,但所有这些数字都是字符串,所以我使用了split(),然后将其转换为double。如何将其转换为双2D阵列

1.65 4.50 2.36 7.45 3.44 6.23

2.22-3.24-1.66-5.48-3.46

4.23 2.29 5.29

2.763.764.295.483.43

3.38 3.65 3.76

2.46 3.34 2.38 8.26 5.34

这就是我目前的情况:

public static void main(String[] a) throws FileNotFoundException {

     File file =  new File("district3.txt");

     Scanner scan = new Scanner(file); 
     String b; 
     String[] c;

     int r = 6;

     double[][]arr = new double[r][];


     while(scan.hasNextLine()) {
        //get number as String
        b = scan.nextLine();

        //split them 
         c = b.split(" ");

         for(String i:c)
            System.out.println(Double.parseDouble(i) );




     } 

}

共 (1) 个答案

  1. # 1 楼答案

    for更改为print内联,然后在打印完所有数字后添加println

    for(String i:c)
                System.out.print(i + " ");
    
    System.out.println()
    

    要存储数字,可以执行以下操作:

    double[][]arr = new double[r][];
    
    int i = 0;
    while(scan.hasNextLine()) {
    
        //get number as String
        b = scan.nextLine();
    
        //split them 
        c = b.split(" ");
        arr[i] = new double[c.length];
        for(int j = 0; j < c.length; ++j) {
            arr[i][j] = Double.parseDouble(c[j]);
            // Display them if needed
            System.out.print(c[j] + " ");
        }
        System.out.println();
        ++i;
     }