Java,输入文件到2D数组

时间:2013-10-05 11:23:37

标签: java arrays

我是Java新手。我正在尝试从输入文件中获取值,这是我在eclipse中创建的,并尝试将它们保存到2D数组中。输入是:

31 22 23 79

20 -33 33 1

3 -1 46 -6

我可以将它保存到常规数组中,但无论我尝试什么,我都无法弄清楚如何将其保存到上面的表格中的二维数组。我尝试了循环,但它为循环的每次迭代保存了所有12个数字。我尝试使用变量,只是像常规数组一样递增它们,它只是没有保存。有关如何做到这一点的任何帮助,常规数组的代码如下,打印以下屏幕:

[31,22,23,79,20,-33,33,1,3,1,46,-6]

import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

public class ArrayMatrix2d {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    if (args.length == 0){
        System.err.println("Usage: java Sum <filename>");
        System.exit(1);
    }

    try {
        //int[][] matrix = new int[3][4];
        int MyMat[] = new int[12];
        int num = 0;

        //int row = 0;
        //int column = 0;
        BufferedReader br = new BufferedReader(new FileReader(args[0]));
        String line;
        while((line = br.readLine()) != null) {
            StringTokenizer st = new StringTokenizer (line);
            while (st.hasMoreTokens()){
                int value1 = Integer.parseInt(st.nextToken());
                MyMat[num] = value1;
                num++;              
            }
        }
        System.out.println(Arrays.toString(MyMat));
        br.close();
    }       
    catch(Exception e) {}           
}

}

3 个答案:

答案 0 :(得分:1)

如果您使用Java 7,则可以将文本文件加载到List。据我所知,这是创建String [] []

的最短路径
String[][] root;

List<String> lines = Files.readAllLines(Paths.get("<your filename>"), StandardCharsets.UTF_8);

lines.removeAll(Arrays.asList("", null)); // <- remove empty lines

root = new String[lines.size()][]; 

for(int i =0; i<lines.size(); i++){
  root[i] = lines.get(i).split("[ ]+"); // you can use just split(" ") but who knows how many empty spaces
}

现在您已填充root[][]

希望它能帮到你

答案 1 :(得分:1)

你可以像这样matrix

int[][] matrix=new int[3][]; //if the number of columns is variable

int[][] matrix=new int[3][4]; //if you know the number of columns

并在循环中获得

 int i=0;
 while((line = br.readLine()) != null) {
        StringTokenizer st = new StringTokenizer (line);
        int num=0;
        //the next line is when you need to calculate the number of columns
        //otherwise leave blank
        matrix[i]=new int[st.countTokens()];
        while (st.hasMoreTokens()){
            int value1 = Integer.parseInt(st.nextToken());
            matrix[i][num] = value1;
            num++;              
        }
        i++;
 }

答案 2 :(得分:0)

怀着希望,我的代码将对您有用:

java.util.Scanner scan = new java.util.Scanner(System.in);
int [] ar= Arrays.stream(scan.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int m=ar[0];
int n=ar[1];
int myArray[][]=new int[m][n];
for (int i = 0; i < m; i++)
    myArray[i]= Arrays.stream(scan.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
相关问题