Java,将文件输入2D数组 [英] Java, input file to 2D array

查看:46
本文介绍了Java,将文件输入2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的是Java新手。我正在尝试从我在Eclipse中制作的输入文件中获取值,然后尝试将其保存到2D数组中。输入为:

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:

31 22 23 79

31 22 23 79

20 -33 33 1

20 -33 33 1

3 -1 46 -6

3 -1 46 -6

我可以将其保存到常规数组中,但是不管我尝试什么,我都无法确定了解如何将其保存到上述表单中的2d数组中。我尝试了循环,但是它为循环的每次迭代保存了全部12个数字。我试着使用变量,只是像常规数组那样递增变量,却什么也没保存。有关如何执行此操作的任何帮助,下面是常规数组的代码,将以下内容显示在屏幕上:

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:

[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) {}           
}

}

推荐答案

您可以像这样制作矩阵

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++;
 }

这篇关于Java,将文件输入2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆