0

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

}

3 Answers 3

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++;
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help. I'm getting the following output now: [[31, 22, 23, 79], null, null]. I've probably made a typo or something, will try track it down, but definitely going in the right direction.
Seems like your second and third row aren't constructed.
Aha, got it, thanks a million. Just had my print statement in the wrong place. Thank you!
1

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

3 Comments

Hi, I really appreciate the help but my Java is so basic that I just don't understand what's going on here. Thanks though!
You can try to debug and observe how it works. With only 1st row you put file name and get List of lines. 2nd row removes all empty rows in file. So you cut off your code from 20 rows to 4
I'll try it out and see how it works, I'm definitely trying to learn anyway. Thanks!
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.