Convert 2D array to string and back again in Java? - java

I need to store a 2d enum array in an sqlite database on Android so the easiest way seems to be to convert into a string (e.g. a CSV string) to store in the db and then back again when retrieving.
How can I do this in java?
MyEnum[][] myArray;
Thanks

If you want to convert the whole 2d-array into a single String, you could use a CSV-type encoding, but you'd have to protect any special character (typ. the comma-separator) in order not to mess up field separation. A quick (and dirty?) way to do it would be to use enc = URLEncoder.encode(val, "UTF-8") on each value, and then back with val = URLDecoder.decode(enc, "UTF-8").
You would also have to use another separator (e.g. \n) to separate lines:
String write(MyENum[][] myArray) {
String res = "";
for (int iRow = 0; iRow < myArray.length; iRow++) {
for (int iCol = 0; iCol < myArray[iRow].length; iCol++)
res += URLEncoder.encode(myArray[iRow][iCol].name(), "UTF-8")+",";
res += "\n";
}
}
(I'll let it to you not to add the extra "," at the end of each line). Then, to read back:
MyEnum[][] read(String res) {
String[] rows = res.split("\n");
MyEnum[][] myArray = new MyEnum[rows.length][];
for (int iRow; iRow < rows.length; iRow++) {
String[] cols = rows[iRow].split(",");
myArray[iRow] = new MyEnum[cols.length];
for (int iCol = 0; iCol < cols.length; iCol++)
myArray[iRow][iCol] = MyEnum.valueOf(URLDecoder.decode(cols[iCol], "UTF-8"));
}
return myArray;
}
That is all based on the fact that there are name() and valueOf() methods available in your enum to make the transformation, as #sean-f showed you in the post he linked.

Related

CSV input to two dimmensional array in java

I have a read() method and inside I want to separate the Strings(which have spaces between them) and putting them in a two dimensional array, but before that I get rid of all the spaces. After the array initialized, it is given to the CSV constructor and that is creating its own 2D array.
The problem is that I always get the following error: "variable sr might not have been initialized" at CSV csv = new CSV(sr).
How do I make sure that my array gets the valid String?
private String[][] tomb;
private CSV(String[][] t2) {
tomb = new String[t2.length][];
for(int i = 0; i < t2.length; i++) {
tomb[i] = new String[t2[i].length];
for(int j = 0; j < t2[i].length; j++) {
tomb[i][j] = t2[i][j];
}
}
}
public static CSV read(Scanner sc) {
String[][] sr;
int n = 0;
while (sc.hasNextLine())
{
String line = sc.nextLine();
String[] str = line.split(",");
sr = new String[str.length][];
for (int i = 0; i < str.length; i++) {
sr[i][n].replaceAll("\\s+","");
}
n++;
}
CSV csv = new CSV(sr);
return csv;
}
You can resolve the error by setting sr to null in the initialization:
String[][] sr = null;
If you want to make sure sr was set correctly, you can check if sr is still null after the while loop completes.

[ERROR]java.lang.ArrayIndexOutOfBoundsException:1

I have executed the below java script in the informatica java transformation but I'm getting the error: [ERROR]java.lang.ArrayIndexOutOfBoundsException:1
String [] Name_parsed;
String Name_delimiter = "&";
String Name_li = Name;
int Name_length = Name_li.length();
for (int i=0; i < Name_length; i++)
{
Name_parsed = Name.split(Name_delimiter);
o_Name =Name_parsed[0];
generateRow();
o_Name =Name_parsed[1];
generateRow();
}
Chances are, your input string has fewer than 1 & character. Try printing the Name variable to see if this is the case. You can always wrap this in a try/catch block to handle these cases.
The error mean that you have array that length is lower then 1.
This mean that Name.split(Name_delimiter) return array with only one element.
and when you try to access to index 1 here o_Name =Name_parsed[1]; it can not found it.
Validate your input data.
If there can be variable number of "&"(s) in the Name field, you should do it like this:
String [] Name_parsed;
String Name_delimiter = "&";
String Name_li = Name;
int Name_length = Name_li.length();
for (int i=0; i < Name_length; i++)
{
Name_parsed = Name.split(Name_delimiter);
for (int j=0; j<Name_parsed.length; j++){
{
o_Name =Name_parsed[j];
generateRow();
}
}

How to break a string into many variables

Is it possible in Java to break a String into many individual int variables?
String s = "1,2,3,4,5,6";
Like
int var1 = 1;
int var2 = 2;
int var3 = 3;
and so on.
Thanks
String s = "1,2,3,4,5,6";
String[] vars = s.split(",");
int [] varIn= new int[vars.lenght]
for (int i=0;i<vars.lenght;i++)
{
varIn[i]= Integer.parseInt(vars[i]);
}
.
==> varIn[0]=1;
varIn[1]=2;
etc..
split() method is more apt one.One of the other way is use StringTokenizer class, as follows
String abc = "1,2,3,4";
int i = 0;
StringTokenizer st = new StringTokenizer(abc,",");
int array[] = new int[st.countTokens()];
while (st.hasMoreTokens()) {
array[i] = Integer.parseInt(st.nextToken().toString());
i++;
}
I know your problem is already solved.But this code snippet is just to introduce use of StringTokenizer
You cannot dynamically allocate the values to each variable unless you use reflection.
What you can do is split the string on the commas, convert each token into an integer and put these values inside a collection.
For example:
int[] result;
String s = "1,2,3,4,5,6";
String[] tokens = s.split(",");
result = new int[tokens.length];
for(int i = 0; i < tokens.length; i++){
result[i] = Integer.parseInt(tokens[i]);
}
Now you can access each value in the result array (perhaps by assigning var1 to result[1]).
As said: you can also add it to the variables directly using reflection but that's usually a sign that your design went wrong somewhere.

extract data from csv file and put to 2D Array - refactoring

I need read data from csv file and much more convinience for me is put there to 2D array (to my mind it's easiest way to work with this "schedule" data).
Each file line contained information in following format:
Instructor, Course, Group, Student, Result
as follows example:
Paul Schwartz,Introduction to Computer Architecture,I1,Ben Dunkin,88
Muhamed Olji,Object Oriented Programming,I4,Mike Brown,73
But my code needs some simplify. But I don't know how to make it easier and ask of You.
Code:
private String[][] fileContent(String pathToCSVFile) {
final int ROWS = 100;
final int COLUMNS = 5;
String fileData[][] = new String[ROWS][COLUMNS];
Scanner scanner = new Scanner(pathToCSVFile);
boolean done = false;
int i, j;
while (!done) {
for (i = 0; i >= 0; i++) {
for (j = 0; j >= 0; j++) {
String str[] = scanner.nextLine().split(",");
for (int element = 0; element < str.length; element++) {
fileData[i][element] = str[element];
if (i >= ROWS) {
Arrays.copyOf(fileData, fileData.length * 2);
}
}
}
}
if (!scanner.hasNextLine()) done = true;
}
return fileData;
}
How to refactor this snippet of code for better simplicity?
Does exist any better way for partially filled array (than Arrays.copyOf(fileData, fileData.length * 2))?
Using openCSV, you can get a list containing all the lines and convert it to an array (or just keep the list):
try (CSVReader reader = new CSVReader(new BufferedReader(
new FileReader(pathToCSVFile)));) {
List<String[]> lines = reader.readAll();
return lines.toArray(new String[lines.size()][]);
}
(using Java 7 try-with-resources syntax)
First of all, be careful with those for loops. They are "almost" undefined loops, because they start with i,j=0, and loop while >=0 (always, until they overflow into a negative number).
And why do you need them anyway? I think with you while and the for(element) you are done, right?
Something like that (I didn't tried, is just to explain the concept)
private String[][] fileContent(String pathToCSVFile) {
final int ROWS = 100;
final int COLUMNS = 5;
String fileData[][] = new String[ROWS][COLUMNS];
Scanner scanner = new Scanner(pathToCSVFile);
boolean done = false;
int i=0;
while (!done) {
String str[] = scanner.nextLine().split(",");
for (int element = 0; element < str.length; element++) {
fileData[i][element] = str[element];
if (i >= ROWS) {
Arrays.copyOf(fileData, fileData.length * 2);
}
}
if (!scanner.hasNextLine())
done = true;
else
i++;
}
return fileData;
}
By the way, why don't you use objects, like an ArrayList? It would make your life easier, so you don't have to worry about memory handling. You just add new objects.
Something like an ArrayList <ArrayList <String>>

Split long string into byte arrays

This is for the level system in a game.
The level consists of two byte arrays:
byte[] tiles and byte[] data
tiles holds the id of the tiles and data holds data.
I created a function to make a string out of them. It's formatted like tileId:tileData,tileId:tileData,tileId:tileData,etc
You can see an example of a complete level here: http://pastebin.com/X2LG7e80
The script looks like this:
public String toString() {
String s = "";
StringBuilder sb = new StringBuilder();
for (int t = 0; t < tiles.length; t++) {
sb.append(tiles[t]).append(":").append(data[t]).append(t == tiles.length - 1 ? ";" : ",");
}
s = sb.toString();
return s;
}
Now I need a way to turn it back into two byte arrays.
I tried a couple of different things but none of them worked.
Assuming a variable stringRep contains the string representation:
String stringRep = "tileId:tileData,tileId:tileData,tileId:tileData";
String[] pairs = stringRep.split(",");
byte[] tiles = new byte[pairs.length];
byte[] data = new byte[pairs.length];
int i = 0;
for(String pair : pairs){
String[] pairParts = pair.split(":");
titles[i] = Byte.parseByte(pairParts[0]);
data[i] = Byte.parseByte(pairParts[1]);
i++;
}

Categories

Resources