user2849168
user2849168

Reputation: 3

Java, input file to 2D array

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

20 -33 33 1

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:

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

}

Upvotes: 0

Views: 775

Answers (3)

Vik Ermolenko
Vik Ermolenko

Reputation: 62

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

Upvotes: 0

Maxim Shoustin
Maxim Shoustin

Reputation: 77930

If you use Java 7 you can load text file to List. As I know this is a shortest way to create 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[][]

Hope it will help you

Upvotes: 1

hamon
hamon

Reputation: 1016

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

Upvotes: 1

Related Questions