Converting a 2d array of ints to char and string in Java - java

How can I convert the ints in a 2d array into chars, and strings? (seperately)
If I copy ints to a char array i just get the ASCII code.
For example:
public int a[5][5]
//some code
public String b[5][5] = public int a[5][5]
Thanks

This question is not very well-phrased at all. I THINK what you're asking is how to convert a two-level array of type int[][] to one of type String[][].
Quite frankly, the easiest approach would simply leave your array as-is... and convert int values to String's when you use them:
Integer.toString(a[5][5]);
Alternatively, you could start with a String[][] array in the first place, and simply convert your int values to String when adding them:
a[5][5] = new String(myInt);
If you really do need to convert an array of type int[][] to one of type String[][], you would have to do so manually with a two-layer for() loop:
String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
converted[index] = new String[a[index].length];
for(int subIndex = 0; subIndex < a[index].length; subIndex++){
converted[index][subIndex] = Integer.toString(a[index][subIndex]);
}
}
All three of these approaches would work equally well for conversion to type char rather than String.

Your code must basically go through your array and transform each int value into a String. You can do this with the String.toString(int) method.
You can try that :
String[][] stringArray = new String[a.length][];
for(int i = 0; i < a.length; i++){
stringArray[i] = new String[a[i].lenght];
for(int j = 0; j < a[i].length; j++){
stringArray[i][j] = Integer.toString(a[i][j]);
}
}

If you want the int number as a string then you can use the Integer.toString() function.
b[1][1] = Integer.toString(a[1][1]);

String [][]b = new String[a.length][];
for(int i=0; i<a.length; i++) {
int [] row = a[i];
b[i] = new String[row.length];
for(int j=0; j<row.length; j++) {
b[i][j] = Integer.toString(row[j]);
}
}

To convert a 2D array into String you can use Arrays.deepToString(stringArr).

Related

Bad operand types for binary operator '+' after trying to fill a new array

I'm trying to put all the integer converted elements into a new array, but I keep getting the error saying "Bad operand types for binary operators "+".
char[] array = input.toCharArray();
int[] myArray;
for (int i = 0, n = array.length; i < n; i++) {
char character = array[i];
int ascii = (int) character;
**myArray** += ascii;
}
I was expecting myArray to get filled with the newly converted integers, but It doesn't work apparently.
First initialise the myArray
int[] myArray = new int[array.length];
Then in the for loop just add int ascii to myArray
myArray[i]=ascii;
And your for loop is also wrong which is invalid, for loop consists of three part (initialisation, condition, increment) i will suggest you to go through some basics on loops concepts
for (int i = 0, i < array.length; i++)
No need to use n = array.length everytime.
char[] array = input.toCharArray();
int[] myArray = new int[array.length];
for (int i = 0; i < array.length; i++)
{
char character = array[i];
int ascii = (int) character;
myArray[i] = ascii;
}

I need to convert an int[][] to a char[][] or create a char[][] of the same dimensions

I have an int[][] that will be initialized by a file so I don't know the size of it. how can I convert it to a 2D char array or create a char[][] of the same size?
Is this along the right lines? how would I do it?
int[][] shade = <a method returns an int[][]>
char[][] converted = new int[shade.length][];
for(int i = 0; i < shade.length; i++) {
converted[i] = new String[shade[i].length];
for(int j = 0; j < shade[i].length; j++){
converted[i][j] = Character.toInt(shade[i][j]);
}
}
you can do that :
String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
converted[index] = new String[a[index].length];
for(int subIndex = 0; subIndex < a[index].length; subIndex++){
converted[index][subIndex] = Integer.toString(a[index][subIndex]);
}
}
Firstly, you need to confirm what kind of char do you need .
I guess you need to convert the int into a char representing in ASCII, that means 65 will be cast to 'A' , you can just use typecast, like
int intvalue=65;
char c=(char)intvalue;//will be 'A'
If you want to convert 5 to '5'(But you need to guarantee that intvalue is within [0,9]) ,use
int intvalue=5;
char c= = (char) ('0' + intvalue); // c is now '5';
Here is the way of your case from int to char representing in ASCII:
public static void main(String agrs[]) {
int[][] shade = getIntArray();//here is how you
char[][] converted = new char[shade.length][shade[0].length];//use the shade's row and column length to declare an char[][] array
for (int i = 0; i < shade.length; i++) {
for (int j = 0; j < shade[i].length; j++) {
converted[i][j] = ((char) shade[i][j]);
System.out.println(converted[i][j]);//out put will be 'A'
}
}
}
//here you need to replace it into your own method, now I pretend that I returns a [2][2] array which holds value of 65 ('A')
private static int[][] getIntArray(){
int[][] array=new int[2][2];
for(int i=0;i<array.length;i++)
for(int j=0;j<array[i].length;j++){
array[i][j]=65;
}
return array;
}

String to int array [][] - JAVA

I have a board game define as
boardArray = new int[4][4];
and I have a string in this format:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]"
Is there a way to put it in the int array? Consider that it should look like this
[0,0,2,0]
[0,0,2,0]
[0,0,0,0]
[0,0,0,0]
You could simply do the following:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]";
String myNums[] = s.split("[^0-9]+");
//Split at every non-digit
int my_array[][] = new int[4][4];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
my_array[i][j] = Integer.parseInt(myNums[i*4 + j + 1]);
//The 1 accounts for the extra "" at the beginning.
}
}
//Prints the result
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++)
System.out.print(my_array[i][j]);
System.out.println();
}
If you want to to it dynamically, I've written a librray: https://github.com/timaschew/MDAAJ
The nice thing is, that it's really fast, because internally it's a one dimensional array, but provides you same access and much more nice features, checkout the wiki and and tests
MDDA<Integer> array = new MDDA<Integer>(4,4);
or initialize with an existing array, which is one dimensional "template", but will be converted into your dimensions:
Integer[] template = new Integer[] {0,0,2,0, 0,0,2,0, 0,0,0,0, 0,0,0,0};
MDDA<Integer> array = new MDDA<Integer>(template, false, 4,4);
//instead of array[1][2];
array.get(1,2); // 2

subtract integer from a string of integers

Suppose I have a string array as follows:
String[] str = {"2","4","5"};
Now I want to subtract 1 from each of its elements, ie, I want the string to be like this now:
str = {"1","3","4"};
How do I do it? Is there any way other than converting it into an integer array?
Try this,
String str[]= {"2","4","5"};
for(int i=0;i<str.length;i++)
{
str[i]=String.valueOf(Integer.parseInt(str[i])-1));
}
You have to convert them into integers, but not necessarily store into an array of integers. You can do the math in-place instead:
for(int i = 0; i < str.length; i++) {
str[i] = Integer.toString(Integer.parseInt(str[i]) - 1);
}
However, this is a code smell to me. Strings do not tend to be the best choice when doing math in general. You might also want to work with an int[] internally and convert them to strings when needed.
You would need to convert them to Integers.
If you could make some crazy constraints, you could get it a little better, for example...
Only having single digit integers in an array of characters, strictly greater than zero. You could then do the "math" by subtracting 1 from their ASCII value, but this is a pretty crazy situation to even ever have.
convert string to int : int foo = Integer.parseInt("1234");
Subtract 1 from it
Convert back to string Integer.toString(i)
That makes
for (int i = 0; i < strn.length; i++)
strn[i] := String.valueOf(Integer.parseInt(strn[i]) - 1);
}
for (int i = 0; i < str.length; i++)
str[i] := String.valueOf(Integer.parseInt(str[i]) - 1);
}
Hope this will helps you.
public String[] stringCal(String[] ele,int numbr){
String[] sCalulated = new String[ele.length];
for(int i = 0; i < ele.length ; i ++){
sCalulated[i] = String.valueOf(Integer.parseInt(ele[i])-numbr);
}
return sCalulated;
}
public static void main(String[] args) throws IOException {
String str[] = subtractOn(new String[]{"2","4","5"});
for(int k=0;k<str.length;k++){
System.out.println("Integer is :" +str[k]);
}
}
public static String[] subtractOn(String str[]){
int intArray[] = new int[str.length];
String stres[] = new String[str.length];
for(int i=0;i<str.length;i++){
intArray[i] = Integer.parseInt(str[i]);
}
for(int j=0;j<intArray.length;j++){
stres[j] = String.valueOf(intArray[j]-1);
}
return stres;
}
You can use org.apache.commons.lang3.math library to solve it in an elegant way.
for(int i = 0; i < str.length; i++) {
str[i] = NumberUtils.toInt(str[i]) - 1;
}

Java: Storing values in 2D Array

I have a problem with storing values in a multidimensional array. The main concept of the idea is that I have an arraylist which is called user_decide and I transform it in a array. So, the decide array looks like [1, 45, 656, 8, 97, 897], but all the rows don't have the same number of elements. Then, I split this replace [,] and spaces and I would like to store each value individually in a 2D array. So, I split it with the "," and try to store each value in a different position. Everything seems to be printed great, even the cut[j] is what I want to store, but I get a java.lang.NullPointerException, which I don't get. The count variable is actually the count = user_decide.size()
String [] decide = user_decide.toArray(new String[user_decide.size()]);
for (int i = 0; i < count; i ++){
decide[i] =
decide[i].replaceAll("\\s", "").replaceAll("\\[","").replaceAll("\\]", "");
}
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Another question is why I cannot store it in a Int [][] array? Is there a way to do that?
Thank you a lot.
** EDIT **
I just made an edit about my answer after I accepted the question. I am trying to store it in a 2D int array.
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length];
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
Ivaylo Strandjev's answer shows the reason for your problem. But there's a much simpler solution:
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
data1[i] = decide[i].split("\\,");
System.out.println(Arrays.toString(data1[i]));
}
Also, you don't need to escape the comma.
EDIT
Saw your edit. There is a big mistake, see my comment in your code:
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length]; // This line has to be prior to the
// inner loop, or else you'll overwrite everything but the last number.
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
If all you want is the int[], this is what I would do:
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
String[] temp = decide[i].split(",");
data[i] = new int [temp.length];
for (int j = 0; j < temp.length; j++){
data[i][j] = Integer.parseInt(temp[j]);
System.out.println(data1[i][j]);
}
}
There are probably nicer ways, but I don't know why you are using user_decide.size() ( a Collection) for the condition and decide[i] (an array) within the loop. There's no good reason I can think of mixing this, as it could lead to errors.
In java you will need to also allocate data[i], before copying contents:
for (int i = 0; i < count; i++){
data1[i] = new String[cut.length];
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Before copying contents:

Categories

Resources