Java,输入文件到2D数组

时间:2021-10-17 21:37:16

I'm really new to Java. I'm trying to take values from an input file, which I made in eclipse, and trying to save them to a 2D array. The input is:

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

31 22 23 79

31 22 23 79

20 -33 33 1

20-33 33 1

3 -1 46 -6

3 -1 46 -6

I can save it to a regular array fine, but not matter what I try I can't figure out how to get it to save to a 2d array in the form above. I tried for loops, but it saved all 12 numbers for each iteration of the loop. I tried using variables and just incrementing them like for the regular array and it just saved nothing. Any help on how to do this appreciated, code for regular array is below, prints the following to screen:

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

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

[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 个解决方案

#1


1  

You could make your matrix like this

你可以像这样制作你的矩阵

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

and in the loop you get

在你得到的循环中

 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


1  

If you use Java 7 you can load text file to List. As I know this is a shortest way to create String[][]

如果使用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
}

Now you have populated root[][]

现在你已经填充了root [] []

Hope it will help you

希望它会对你有所帮助

#3


0  

With hope, that my code will be useful for you:

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

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();

#1


1  

You could make your matrix like this

你可以像这样制作你的矩阵

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

and in the loop you get

在你得到的循环中

 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


1  

If you use Java 7 you can load text file to List. As I know this is a shortest way to create String[][]

如果使用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
}

Now you have populated root[][]

现在你已经填充了root [] []

Hope it will help you

希望它会对你有所帮助

#3


0  

With hope, that my code will be useful for you:

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

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();