Java multidimensional Array to string and String to Array - java

I have array
data[][];
convert to string:
string = Arrays.deepToString(data);
string:
[[1, 1394119227787, 59474093, USD/DKK, true, 0.05, 5.391582, 5.00663, 5.39663, null, null], [1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null]]
and How convert this string back to array?

Try my stringToDeep() method to convert back to Array.
import java.util.*;
public class DeepToArray {
public static void main(String[] args) {
int row, col;
row = 2;
col = 3;
String[][] in = new String[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
in[i][j] = i + " " + j;
}
}
String str = Arrays.deepToString(in);
System.out.println(str);
String[][] out = stringToDeep(str);
for (String s2[] : out) {
for (String s3 : s2) {
System.out.print(s3 + " ");
}
System.out.println();
}
}
private static String[][] stringToDeep(String str) {
int row = 0;
int col = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '[') {
row++;
}
}
row--;
for (int i = 0;; i++) {
if (str.charAt(i) == ',') {
col++;
}
if (str.charAt(i) == ']') {
break;
}
}
col++;
String[][] out = new String[row][col];
str = str.replaceAll("\\[", "").replaceAll("\\]", "");
String[] s1 = str.split(", ");
int j = -1;
for (int i = 0; i < s1.length; i++) {
if (i % col == 0) {
j++;
}
out[j][i % col] = s1[i];
//System.out.println(s1[i] + "\t" + j + "\t" + i % col);
}
return out;
}
}

There is no method in the java API that will automatically convert this back to an array. You could write code to do this yourself, but it would be tricky; this format does not escape special characters like the square brackets, or the commas. It might be easier just to use a format which is designed for encoding and decoding arrays, like JSON.

All the answers I found are 2-dimensional only, so here's my solution to reverse deepToString(...) for any number of dimensions:
Usage example:
String arrString = "[[[0.11695497071135137, 0.8830064157596283, 0.3433854446148375, 0.18825445694298526, 1.0441938749175883, 0.8941633746325311], [-0.089908138214512, 0.39821330927870574, 0.1365997500579524, 0.7008902956765364, 0.9897596683277262, 0.2847717055995359], [0.6450670283688857, 0.01516064860567864, -0.07904927386204857, 0.2703900981351612, 0.45402985012492075, 0.30505608337251183], [0.5122943117220898, 0.008726346575469023, 0.7734611917871235, 0.3051772999891666, 0.5237487372571624, 1.1824105144656751]]]";
String[][][] arr = (String[][][]) reverseDeepToString(arrString);
System.out.println(Arrays.deepToString(arr));
This code converts a string (arrString) into an array, and then the function Arrays.deepToString(...) converts it back into the same string.
Function code:
public static Object reverseDeepToString(String str){
int dimensions = 0;
for(int x = 0; x < str.length(); x++)
if(str.charAt(x) == '[')
dimensions++;
else break;
str = str.substring(dimensions, str.length() - dimensions);
return createArrayRecursive(str, dimensions);
}
private static Object createArrayRecursive(String str, int dimension){
if(dimension == 1)
return str.split(", "); // modify the code here if you want to convert the strings to another variable type
String[] s = str.split(getArraySeparator(dimension));
int[] lengths = new int[dimension];
lengths[0] = s.length;
Object arr = Array.newInstance(String.class, lengths); // and here (see comment above)
for(int x = 0; x < s.length; x++)
Array.set(arr, x, createArrayRecursive(s[x], dimension - 1));
return arr;
}
private static String getArraySeparator(int dimension){
String separator = ", ";
for(int x = 1; x < dimension; x++)
separator = ']' + separator + "\\[";
return separator;
}

Array to string and back to array :P
import java.util.Arrays;
import java.util.Random;
public class arrays {
public static void main(String [ ] args)
{
String[][] in = new String [10][4];
String[][] out = new String [10][4];
arrays nr = new arrays();
for(int i =0; i< 4; i++){
for(int j =0; j< 4; j++){
in[i][j] = nr.Rand(5);
}
}
System.out.println(Arrays.deepToString(in));
// tablica ok
// convert array to string
String line = "";
for(int i =0; i< 4; i++){
for(int j =0; j< 4; j++){
line += in[i][j] + "_";
}
line += ":";
}
System.out.println(line);
// line back to array
String[] xline = line.split(":");
int ss = 0;
for (String str : xline) {
out[ss] = (String[]) str.split("_");
System.out.println("string line>>>" + str);
ss++;
}
System.out.println(Arrays.deepToString(out));
}
public String nextSessionId() {
//private SecureRandom random = new SecureRandom();
//return new BigInteger(130, random).toString(32);
return null;
}
public String Rand(int zz){
char[] chars = "987654321abcdefghijklm111nopqrstuvwxyz0123456789".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < zz; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
// System.out.println(output);
return output;
}
}
:D

Related

Why am I getting NullPointerException on my "plain1.findPosition(iMsg)"?

First Class which is giving me the error. I'm to make an array with the letters A-Z, and then have the user input the keys which it takes and compares each character's position in the array of the key with the position of a user inputted string
import java.util.*;
public class Encrypt{
private Square plain1;
private Square plain2;
private Square Encrypt1;
private Square Encrypt2;
public Encryption(String key1, String key2) {
Square plain1 = new Square();
Square plain2 = new Square();
Square Encrypt1= new Square(key1);
Square Encrypt2= new Square(key2);
}
public String encrypt(String msg) {
String EmpS = "";
String STR = "";
for(int i = 0; i < message.length(); i+=2){
char iMsg = message.charAt(i);
char iMsg2 = message.charAt(i+1);
int[] posRay = plain1.findPosition(iMsg);
int[] posRay2 = plain2.findPosition(iMsg2);
String answer = "" + Encrypt1.getChar(posRay[0], posRay2[1]);
String Combined = "" + answer;
String answer2 = "" + Encrypt2.getChar(posRay2[0], posRay[1]);
String Combined2 = "" + answer2;
String BothCom = Combined + Combined2;
STR = STR.concat(BothCom);
return STR;
}
return STR;
}
2nd class that is responsible for the array
public class Square {
private char[][] matrix;
public Square() {
arr= new char[5][5];
int ascii= 65;
for (int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
arr[i][j] = (char) ascii;
ascii++;
}
}
}
}
public int[] findPosition(char Chart) {
int[] position= new int[2];
position[0] = -1;
popositions[1] = -1;
for (int i = 0; i < 5; i++){
for (int j = 0; i < 5; j++){
if(matrix[i][j] == Chart){
posistion[0] = i;
position[1] = j;
return position;
}
}
}
I'm getting this as an error (everything else works), what's the issue?:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Square.getPos(char)" because "this.plain1" is null
at findPosition.encrypt(Encrypt.java:45)
at IO.printResults(IO.java:101)
at Test.main(Proj8.java:26)
You are not assigning your class variables, you are actually assigning new local variables inside the method. Change to:
public Encryption(String key1, String key2) {
plain1 = new Square();
plain2 = new Square();
Encrypt1= new Square(key1);
Encrypt2= new Square(key2);
}

how to split a string by using charAt and string.length()

only allow charAt method and length method . Thank you so much!
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(3) == ',') {
what should i write here ? ?
}
Your code needs some refactoring, try this:
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
int cutStringIndex;
if (str.charAt(i) == ',') {
cutStringIndex = i;
}
for (int i = 0; i < cutStringIndex(); i++) {
String cutStringOne = "";
cutStringOne = cutStringOne + str.charAt(i);
}
for (int i = cutStringIndex() + 1; i < str.length(); i++) {
String cutStringTwo = "";
cutStringTwo = cutStringTwo + str.charAt(i);
}
cutString = cutStringOne + " " + cutStringTwo;
return cutString;
}
This will take out the comma which appears to be what you were looking for. I only used the two methods you asked for. Essentially this code gets the index of the comma, then reconstructs the two parts of the strings until it reaches the point of the comma, and skips over it. It may need some minor tweaks for your situation but this should be what you're looking for.
It can be done like this, Suppose String s="200,300,450,600" and you have to split given string using charAt() and string.length() method then first add ',' at the end of the string as given in the code below.
String s="200,300,450,600,",str="";
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch!=','){ //checking if particular character is not ','
str+=ch; //storing it in str string
}
else{
System.out.println(str); //printing each string before ',' is found
str="";
}
}
The output of above code will be:200
300
450
600(all the numbers will be printed on next line)
If you want to use only charAt and string.length() then you should try this
void runApp{
String str = "345, 688, 123";
String values[] = strCut(str); //values[0] = 345, values[1] = 688, values[2] = 123
for(String value : values){
System.out.print(value + " ");
}
}
String[] strCut(String str) {
int elements = 1;
int index = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ',')
elements++;
}
String result[] = new String[elements];
for(int i = 0; i < result.length; i++)
result[i] = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ',') {
if(str.charAt(i) != ' ')
result[index] = result[index] + str.charAt(i);
}
else index++;
}
return result;
}
You can do it as follows:
public class Main {
public static void main(String[] args) {
// Test
runApp();
}
static void runApp() {
String str = "345, 688"; // Expected->"345" "688"
String value = strCut(str);
System.out.println(value);// Display the result
}
static String strCut(String str) {
// Initialise result with a "
String result = "\"";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {// Check char at the index, i
// Add " at the end of one number and again " at the start of the next
result += "\" \"";
} else if (str.charAt(i) != ' ') {
result += str.charAt(i);
}
}
// Add " at the end
result += "\"";
// Finally, return result
return result;
}
}
Output:
"345" "688"
if you must want to make use of charAt() then do like below..
ArrayList<String> stringArr= new ArrayList<String>();
int startindex=0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
String partString = str.substring(startindex, i) ;
startindex=i+1;
stringArr.add(partString);
}
}
String lastString = str.substring(startindex, str.length()) ;
stringArr.add(lastString);
OR
You can simply use split method like below
String[] parts = string.split(",");
String part1 = parts[0]; // 345
String part2 = parts[1]; // 688
You can achieve it by simply doing this,
This will give you the desired result.
String str = "345,688";
ArrayList<String> stringArray = new ArrayList<>();
int startindex=0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ',') {
String subStr = str.substring(startindex, i);
startindex = i+1;
stringArray.add(subStr);
}
}
stringArray.add(str.substring(startindex));

Java : How to add an int to digits in an alphanumeric string and return the output

Trying to increment the digits in an alphanumeric string by a number n and return the result with the increased digits in the same position in the string index. If the digit is 9, the output should wrap to 0, 1, 2, 3,.... and so on to 9
`ie String input = "abc123de45"
n = 2
print = "abc345de67"
for (int i = 0; i < this.inputString.length(); i++) {
char tempInp = this.inputString.charAt(i);
if (Character.isDigit(tempInp)) {
sumDigit = tempInp + n;
}
}
}
return sumDigit;
}
You can use a combination of a StringBuilder and converting the char to the relevant int value
String inputString = "abc123de45";
int n = 2;
StringBuilder buf = new StringBuilder ();
for (int i = 0; i < inputString.length(); i++) {
char tempInp = inputString.charAt(i);
if (Character.isDigit(tempInp)) {
buf.append ((tempInp -'0') + n);
}
else {
buf.append(tempInp);
}
}
System.out.println(buf.toString());
output
abc345de67
You could try using the StringBuilder to update the string when the if statement is true.
public static StringBuilder numericInt(String a,int b)
{
StringBuilder c = new StringBuilder(a);
for (int i = 0; i < c.length(); i++) {
char tempInp = c.charAt(i);
if (Character.isDigit(tempInp)) {
int temp=(c.charAt(i)-'0')+b;
c.setCharAt(i,(char)(temp+'0'));
}
}
return c;
}
}

How do you shift char values in an arraylist?

I'm trying to code a cipher project where the objective is for a user to send in a text and shift number. The result would be printed accordingly. For instance, if I sent "Hello World" with a shift value of 1, it should print: "Gfmmp Xrsme". The problem is that I'm having trouble with the shifting because I have an arraylist of char values (the alphabet).
This is what I have so far:
import java.util.ArrayList;
public class CaesarCipher
{
int shift;
String inputText;
ArrayList<String> arr;
ArrayList<String> exchange = new ArrayList<String>();
public CaesarCipher()
{
shift = 0;
inputText = "";
}
public CaesarCipher(int s, String iT)
{
shift = s;
inputText = iT;
}
public void alphabet()
{
arr = new ArrayList<String>();
arr.add("A");
arr.add("B");
arr.add("C");
arr.add("D");
arr.add("E");
arr.add("F");
arr.add("G");
arr.add("H");
arr.add("I");
arr.add("J");
arr.add("K");
arr.add("L");
arr.add("M");
arr.add("N");
arr.add("O");
arr.add("P");
arr.add("Q");
arr.add("R");
arr.add("S");
arr.add("T");
arr.add("U");
arr.add("V");
arr.add("W");
arr.add("X");
arr.add("Y");
arr.add("Z");
}
public void convert()
{
String revisedText = inputText.replaceAll("\\s","");
//Turn revisedText into an array and match it with array above
revisedText.toUpperCase();
int j = 1;
String letter = "";
for (int i = 0; i < revisedText.length(); i++)
{
exchange.add(revisedText.substring(i, j));
j++;
}
}
public void shift()
{
shift = shift % 26 + 26;
ArrayList<String> newArr = new ArrayList<String>(); // array with shifted values
int pos = 0;
for(int r = 0; r < exchange.size(); r++)
{
if(arr.get(r).equals(exchange.get(r)))
arr.indexOf(r) + shift = pos;
}
}
public String toString()
{
return "";
}
}
Here is quick for loop for an example
String string = "Hello World";
String newPhrase = "";
int shift = 1;
for(int i = 0; i < string.length(); i++){
if(string.charAt(i) != ' ')
newPhrase += (char)(string.charAt(i) + shift);
else
newPhrase += ' ';
}
System.out.println(string + " -> " + newPhrase);
Output
Hello World -> Ifmmp Xpsme
However you should note that there are a couple edge cases i am not checking for. Once you understand the above code you should be able to find the edge cases I am talking about.

Java Read Each Line Into Separate Array

I have 1,000 lines of data in a text file and I would like each line to be its own float [].
1,1,1,1,1,1
2,2,2,2,2,2
3,3,3,3,3,3
Would result in:
float[0] = {1,1,1,1,1,1}
float[1] = {2,2,2,2,2,2}
float[2] = {3,3,3,3,3,3}
Is this possible? I could only find examples of loading an entire file into an array. I tried hardcoding all the arrays, but exceeded the byte character limit of ~65,000
Try the following:
// this list will store all the created arrays
List<float[]> arrays = new ArrayList<float[]>();
// use a BufferedReader to get the handy readLine() function
BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"));
// this reads in all the lines. If you only want the first thousand, just
// replace these loop conditions with a regular counter variable
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String[] floatStrings = line.split(",");
float[] floats = new float[floatStrings.length];
for (int i = 0; i < floats.length; ++i) {
floats[i] = Float.parseFloat(floatStrings[i]);
}
arrays.add(floats);
}
Note that I haven't added any exception handling (readLine(), for example, throws IOException).
use a LineIterator to read each line without loading the whole file
for each line, use a regular expression to extract figures like (\d\.)+ and iterator over the matches found with methods like find() and group()
<body>
<pre>
import java.io.FileReader;
public class Check {
public static void main(String[] args) {
readingfile();
}
public static void readingfile() {
try {
FileReader read = new FileReader("D:\\JavaWkspace\\numbers.txt");
int index;
String nums1 = "";
while ((index = read.read()) != -1) {
if (((char) index) != '\n') {
nums1 += String.valueOf((char) index);
}
}
System.out.println("Problem statement: Print out the greatest number on each line:\n" + nums1);
String f = nums1.substring(0, 14);
String s = nums1.substring(15, 29);
String t = nums1.substring(30);
String[] fs = f.split(",");
int size = fs.length;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = Integer.parseInt(fs[i]);
}
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
System.out.println("\nGreatest number in the first line is:" + (max));
String[] sstr = s.split(",");
int size2 = sstr.length;
int[] arr2 = new int[size2];
for (int i = 0; i < size2; i++) {
arr2[i] = Integer.parseInt(sstr[i]);
}
int max2 = arr2[0];
for (int i = 0; i < arr2.length; i++) {
if (max2 < arr2[i]) {
max2 = arr2[i];
}
}
System.out.println("\nGreatest number in the second line is:" + (max2));
String[] str3 = t.split(",");
int size3 = str3.length;
int[] arr3 = new int[size3];
for (int i = 0; i < size3; i++) {
arr3[i] = Integer.parseInt(str3[i]);
}
int max3 = arr3[0];
for (int i = 0; i < arr3.length; i++) {
if (max3 < arr3[i]) {
max3 = arr3[i];
}
}
System.out.println("\nGreatest number in the third line is:" + (max3));
read.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
</pre>
</body>
Loop over the line-delimited contents of the file with .split("\n") and then cast each result as float array. Here's how to convert the string into a float for you => http://www.devdaily.com/java/edu/qanda/pjqa00013.shtml

Categories

Resources