2

I have text file as

    0B85     61
    0B86     6161
    0B86     41
    0B87     69
    0B88     6969
    0B88     49
    0B89     75
    0B8A     7575
    0B8F     6565

I want to write this string into two dimensional array. (i.e) String read[0][0]=0B85 and String read[0][1]=61. Please suggest any idea to do this using java. Thanks in advance.

2
  • Please post the code you have written so far. People generally do not like to just write your code for you. Commented May 17, 2010 at 7:18
  • yeah, just write it and if you have any problem, post the problem. It is as simple and easy as a small homework Commented May 17, 2010 at 7:21

2 Answers 2

6

Something like this works:

String s = "0B85 61 0B86 6161 0B86 41 0B87 69 0B88"
    + " 6969 0B88 49 0B89 75 0B8A 7575 0B8F 6565";
String[] parts = s.split(" ");
String[][] table = new String[parts.length / 2][2];
for (int i = 0, r = 0; r < table.length; r++) {
    table[r][0] = parts[i++];
    table[r][1] = parts[i++];
}
System.out.println(java.util.Arrays.deepToString(table));
// prints "[[0B85, 61], [0B86, 6161], [0B86, 41], [0B87, 69],
//   [0B88, 6969], [0B88, 49], [0B89, 75], [0B8A, 7575], [0B8F, 6565]]

Essentially you split(" ") the long string into parts, then arrange the parts into a 2 column String[][] table.

That said, the best solution for this would be to have a Entry class of some sort for each row, and have a List<Entry> instead of a String[][].


NOTE: Was thrown off by formatting, keeping above, but following is what is needed

If you have columns.txt containing the following:

    0B85     61
    0B86     6161
    0B86     41
    0B87     69
    0B88     6969
    0B88     49
    0B89     75
    0B8A     7575
    0B8F     6565

Then you can use the following to arrange them into 2 columns String[][]:

import java.util.*;
import java.io.*;
//...

    List<String[]> entries = new ArrayList<String[]>();
    Scanner sc = new Scanner(new File("columns.txt"));
    while (sc.hasNext()) {
        entries.add(new String[] { sc.next(), sc.next() });
    }
    String[][] table = entries.toArray(new String[0][]);
    System.out.println(java.util.Arrays.deepToString(table));

I will reiterate that a List<Entry> is much better than a String[][], though.

See also

  • Effective Java 2nd Edition, Item 25: Prefer lists to arrays
  • Effective Java 2nd Edition, Item 50: Avoid strings where other types are more appropriate
Sign up to request clarification or add additional context in comments.

Comments

0

Something like (Pseudo code):

parts = yourData.split()
out = new String[ parts.length/2 ][2];
int j=0;
for i=0, i < parts.length -1, i+2:
  out[j][0] =  parts[i]
  out[j][1] = parts[i+1] 
  j++

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.