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++;
}
Related
I've tried creating many variations, I tried switching the nested for loops and I tried storing it in a temp value but to know avail, this is a test code of my original code that will invoke multiple methods and I dont want it to get overwritten
public class Main {
public static void main(String[] args) {
char[] memoryArray = new char[24];
String s = new String("hello");
int start = 0;
int length = s.length();
String d = new String("world");
int length1 = d.length();
char tmp;
for (int i = start; i < length - start; i++) {
if (memoryArray[i] == '\u0000') {
memoryArray[i] = s.charAt(i);
}
}
start = start + length;
for (int i = 0; i < length1; i++) {
tmp = d.charAt(i);
for (int j = start; j < start + length1; j++)
if (memoryArray[j] == '\u0000') {
memoryArray[j] = tmp;
}
}
System.out.println(memoryArray);
}
}
expected output helloworld
In your particular case you know what the two strings are, hello and world, but what if you didn't know what strings those variables will hold?
The easiest solution to create the array would be to:
Concatenate the strings together into a new String variable;
Declare the memoryArray and place each character within the new concatenated string into that array;
Display the contents of memoryArray.
With this in mind:
String a = "hello";
String b = "programming";
String c = "world";
// Concatenate the strings together
String newString = new StringBuilder(a).append(b).append(c).toString();
// Declare memoryArray and fill with the characters from newString.
char[] memoryArray = newString.toCharArray();
// Display the Array contents
System.out.println(memoryArray);
But if you want to utilize a for loop for this sort of thing then these steps can do the trick:
Concatenate the strings together into a newString String variable;
Declare the memoryArray and initialize it based on the newString length;
Create a for loop to iterate through the newString one character at a time;
Within the loop, add each character to the memoryArray character array;
Display the contents of memoryArray.
With this in mind:
String a = "hello";
String b = "programming";
String c = "world";
// Concatenate the strings together
String newString = new StringBuilder(a).append(b).append(c).toString();
// Declare and initialize the memoryArray array based on the length of newString.
char[] memoryArray = new char[newString.length()];
// Iterate through newString and fill memoryArray
for (int i = 0; i < newString.length(); i++) {
memoryArray[i] = newString.charAt(i);
}
// Display the Array contents
System.out.println(memoryArray);
I have this task to mask the contents of a .CSV file using Java. Done with masking other field but the problem is masking the data in the Primary Key column.
I tried using the code below but it doesn't work. How should I do it?
String str = src.replaceAll("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "QLBNAVHTROFSEJMIKWPYGDUCZX");
There are a number of ways you could do this, but regular expressions are not the approach I would choose. I would build a map of character to character and then iterate the characters in a given string building the transposed output with the map (and don't forget digits and lowercase letters). Something like,
private static Map<Character, Character> MASK_MAP = new HashMap<>();
static {
String inChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
outChars = "QLBNAVHTROFSEJMIKWPYGDUCZX";
inChars += inChars.toLowerCase() + "0123456789";
outChars += outChars.toLowerCase() + "8652103749";
for (int i = 0; i < inChars.length(); i++) {
MASK_MAP.put(inChars.charAt(i), outChars.charAt(i));
}
}
private static String maskKey(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
sb.append(MASK_MAP.get(s.charAt(i)));
}
return sb.toString();
}
And then call
String out = maskKey(inputString);
I have a text file with this structure:
CRIM:Continuius
ZN:Continuius
INDUS:Continuius
CHAS:Categorical
NOX:Continuius
I inserted it into a two dimensional array:
BufferedReader description = new BufferedReader(new FileReader(fullpath2));
String[][] desc;
desc = new String[5][2];
String[] temp_desc;
String delims_desc = ":";
String[] tempString;
for (int k1 = 0; k1 < 5; k1++) {
String line1 = description.readLine();
temp_desc = line1.split(delims_desc);
desc[k1][0] = temp_desc[0];
desc[k1][1] = temp_desc[1];
}
and then tried to identify which attribute is Categorical:
String categ = "Categorical";
for (int i=0; i<5; i++){
String temp1 = String.valueOf(desc[i][1]);
if ("Categorical".equals(desc[i][1])){
System.out.println("The "+k1+ " th is categorical.");
}
}
Why doesn't it return true, although one of the attributes is categorical?
Looking at the input you posted (in the edit perspective), I saw there is a lot of trailing whitespace on almost every line of the textfile. Your problem will disappear if you replace
desc[k1][1] = temp_desc[1];
with
desc[k1][1] = temp_desc[1].trim();
You could even shorten your code to
for (int k1 = 0; k1 < 5; k1++) {
String line1 = description.readLine().trim();
desc[k1] = line1.split(delims_desc);
}
Clarification:
You are trying to compare
"Categorical" // 11 characters
with
"Categorical " // more than 11 characters
and those are not equal strings.
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.
I'm trying to do some work on Mobile apps.
I have parser in class: A
for (int i = 0; i < jArray3.length(); i++) {
news_id = Integer.parseInt((json_data.getString("news_id")));
news_title = json_data.getString("news_title");
}
I have to parse and get value of id and title. Now I want to store this title in array and call another class. In that class we have to convert that array into String so that i can print that title value in single line.
How can I implement this can u post some code for me?
Based on my understanding of your question, I assume the following snippet only you are looking for.
String[] parsedData = new String[2];
for (int i = 0; i < jArray3.length(); i++) {
news_id = Integer.parseInt((json_data.getString("news_id")));
news_title = json_data.getString("news_title");
}
parsedData[0] = news_id;
parsedData[1] = news_title;
DifferentCls diffCls = new DifferentCls(data);
System.out.println(diffCls.toString());
DifferentCls.java
private String[] data = null;
public DifferentCls(String[] data) {
this.data = data;
}
public String toString() {
return data[1];
}
news_title = json_data.getString("news_title");
Add line after the above line to add parse value int0 string array
String[] newRow = new String[] {news_id ,news_title};
//Convert array to String
String asString = Arrays.toString(newRow )
1. I am assuming that you have more than one title to be stored.
I am using ArrayList<String> which is more flexible than Array.
Creating an ArrayList and Storing all the title values:
ArrayList<String> titleArr = new ArrayList<String>();
for (int i = 0; i < jArray3.length(); i++) {
news_id = Integer.parseInt((json_data.getString("news_id")));
news_title = json_data.getString("news_title");
titleArr.add(news_title);
}
2. Now sending it to another class, where you need to Show all the titles in Single Line.
new AnotherClass().alistToString(titleArr);
// This line should be after the for-loop
// alistToString() is a method in another class
3. Another class structure.
public class AnotherClass{
//.................. Your code...........
StringBuilder sb = new StringBuilder();
String titleStr = new String();
public void alistToString(ArrayList<String> arr){
for (String s : arr){
sb.append(s+"\n"); // Appending each value to StrinBuilder with a space.
}
titleStr = sb.toString(); // Now here you have the TITLE STRING....ENJOY !!
}
//.................. Your code.............
}