Converting 1-D String array to 2-D char array - java

I'm working on a program that requires me to take in a 1-D String array from a file and turn it into a 2-D array. Taking in the array from the file works fine, but I can't get the second part to work.
The code I'm working with is:
char[][] array2 = new char [7][5];
for (int i = 0; i < array1.length; i++)
{
array2[i]= array[i].toCharArray();
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
{
System.out.println(array2[i][j]);
}
}
The array is supposed to print in a grid format, but is printing downward.
Any help is appreciated, thanks.

Use print instead of println in inner loop and after each loop print a blank line with println.
for (int i = 0; i < 7; i++) // see changes 5/7. You did "new char[7][5]" not [5][7]
{
for (int j = 0; j < 5; j++) // see changes 7/5
{
System.out.print(array2[i][j]);
}
System.out.println();
}
Update:
Following is a program that convert String array to 2D char array.
public class StringToChar {
public static void main(String[] args) {
String[] strArr = { "HELLO", "WORLD" };
char[][] char2D = new char[strArr.length][];
for (int i = 0; i < strArr.length; i++) {
char2D[i] = strArr[i].toCharArray();
}
for (char[] char1D : char2D) {
for (char c : char1D)
System.out.print(c + " ");
System.out.println();
}
}
}

few suggestions,
replace char[][] array2 = new char [7][5]; with char[][] array2 = new char [array1.length][]; (where array1 holds your strings), so your 2d array will have as many rows as you have strings
your loop
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
....
}
change to
for (int i = 0; i < array2.length; i++)
{
for (int j = 0; j < array2[i].length; j++)
....
another thing is if you want your string printed in rows, use System.out.print, and whenever you finished inner loop, print out'\n' character

You are using println, which is why each character is printed on its own line. You must use print instead.
Note that your initialization with
new char [7][5];
doesn't work as you expect because the inner arrays will be overwritten. Use
new char[7][]
for the same result, but more clarity as to your intent. Here
for (int i = 0; i < 5; i++)
for (int j = 0; j < 7; j++)
you have apparently reversed the order of indices: you are iterating only through 5 outer arrays, but you have allocated 7. What you should do instead is check against the actual array length and not a hardcoded number. The inner array may be of any size, after all (it depends on the string length).

Have a look at the String.toCharArray()
If it is printing downwards then change
for (int i = 0; i < 7; i++) //row loop
{
for (int j = 0; j < 5; j++) //column loop
{
System.out.print(array2[i][j]);
}
System.out.println(); //add here
}
Have a look at
formatting
print vs println

Related

Filling 2D Array in Java and getting ExceptionOutOfBounds

I searched some entries, but could not answer my question correctly myself.
I'm trying to fill a 2-dimensional array with values.
As a test I'm currently doing this by trying to fill the array with the int number 1.
I do not understand my mistake.
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
Use index 0 to length-1 (as array index start with 0)
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
}
just debug it and you can see, that
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
i, and j change values from 0 to 6, it means that it get's out of arrays bounds ( you iterate over 7 lements, instead of 6 ), just remove = sign in loop bodies
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
Your board array is of size 6x6 hence the board.length is 6.
When you run the loop for (int j = 0; j<=board.length; ij+) it will run from 0 up to 6 but the array indexing is from 0 to 5. So when j=6, ExceptionOutOfBounds occurs since it will be referring to index board[0][6].
Change the condition in both the loops from <=board.length to <board.length

Java save alphabet to array

I try save alphabet A-Z to my array, but I don't understand, why I get only this output: Z.
public class Main {
public static void main(String[] args) {
char []tab = new char[25];
for (int i = 0; i<25; i++) {
for (int j=65; j<91; j++) {
tab[i] = (char)j;
}
}
for (int i=0; i<25; i++) {
System.out.println(tab[i]);
}
}
}
Your algorithm is wrong.
Check this simpler solution:
public static void main(String[] args)
{
char []tab = new char[25];
for (int i = 0; i<25; i++) {
tab[i] = (char)(i+65);
}
for (int i=0; i<25; i++) {
System.out.println(tab[i]);
}
}
Your code puts all the letters from A to Z in each slot of the tab array, when executing the 'j' loop, that's why you have only Zs.
You don't need nested loop, try this:
char[] tab = new char[26];
for (int i = 0, j = 65; j < 91; j++, i++) {
tab[i] = (char) j;
}
for (int i = 0; i < 26; i++) {
System.out.println(tab[i]);
}
Also, array size should be 26 not 25.
Lets see how your code works:
for (int i = 0; i<25; i++) { //1
for (int j=65; j<91; j++) { //2
tab[i] = (char)j; //3
} //4
} //5
1) Outer loop sets i=0,
2) Inner loop sets j=65
3) (char)65 represents 'A' ant is placed in tab[0]
2) Inner loop sets j=66
3) (char)66 represents 'B' and is also placed in tab[0]
Here you should notice the problem, which is that inner loop is working on same i, so while iterating over A...Z it is modifying same array location, which means that location will hold last value placed there, which is 'Z'.
(BTW i<25 should be i<26)
Possible solution
don't use inner loop, you can calculate value which should be placed at index by adding i to 65 which in Unicode Table is codepoint of 'A'
for (int i=0; i<26; i++)
tab[i] = (char)(65+i);
BTW you can farther improve readability of this code by avoiding magic numbers (more info: What is a magic number, and why is it bad?). So this code can be rewritten into something like:
int amountOfLetters = 'Z' - 'A' + 1;
char[] tab = new char[amountOfLetters];
int i = 0;
for (char ch = 'A'; ch <= 'Z'; ch++) {
tab[i++] = ch;
}
System.out.println(new String(tab));

Why can't variable j initialization be in the termination expression of the for loop?

public class Gameboard
{
public char[][] board;
public static void main(String args[])
{
Gameboard blank = new Gameboard(false);
System.out.println("Printing blank gameboard:\n" + blank + "\n");
}
public Gameboard(boolean setup)
{
char[][] board = new char[8][8];
if (!setup)
{
for(int i = 0; i < board.length;i++)
{
for(int j = 0; j < board[j].length;j++)//critical condition
{
board[i][j] = '-';
}
}
}
}
}
I know that column length is being used not the row length but the 2d array has the same length row-wise and column-wise.
your logic is off here, since i counts through the first dimension and j through the second: what you really wanted was
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++)
{
board[i][j] = '-';
}
}
this issue of course was in the following line:
for (int j = 0; j < board[j].length; j++)
You are using j as the index on the first dimension of the board array but defining it as a value which goes up to a maximum length equal to the length of the second dimension. Which of course opens you up to the chance of having an index out of range, which is exactly what this code produces.
The reason you have a problem despite the fact that both dimensions are the same is because the conditional for the for loop to exit reevaluates each loop.
The logic is:
j < board[j].length
So at 7 you get:
7 < board[7].length
which is the same as:
7 < 8
Great it passes so goes through another loop but what happens at 8?
8 < board[8].length
Well 8 is out of bounds for the board array so it throws an exception, it simply cant evaluate it. the variable i however never reaches 8, it stops at 7, so you never get an index out of bounds in that case.
If you did the following it would work (but bad practice):
for(int j = 0; j < board[0].length; j++)

how to convert nested loop to 2D array

i would ask if there is some way to print some thing called (Star pattern)!
for(int x=1; x<=5; x++)
{
for(int y=1; y<=x; y++)
{
System.out.print("*");
}
System.out.println();
}
the output (i guess...)
*****
****
***
**
*
so...
could you tell me please, it is possible to print same with array 2d?
thank you for help!
Yes: it's possible. You have to crate an array of 5x5 and fill previously with stars and spaces. Then you have to create a function to print that array.
Did you mean creating and handling arrays that consist of arrays of different sizes? Then it might look, for example, like the following:
public class TestArray {
public static void main(String... args) {
// Create and fill the array we need
char[][] array = new char[5][]; // Create an array of 5 arrays
for (int i = 0; i < array.length; i++) {
array[i] = new char[i+1]; // Each item of the array is a new array of a new size
for (int j = 0; j < array[i].length; j++)
array[i][j] = '*'; // fill the new array with stars
}
// Print the contents of the array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) // Each item is an array
System.out.print(array[i][j]); // print its contents
System.out.println(); // new line
}
}

How to create two dimensional grid with two-d. array?

This is my current code:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
/*for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + "");
}
}*/
}
}
I can't seem to do it. I got confused and I removed the part of testing w/commenting. Just ignore that.
I am aiming to get a two dimensional array like this:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
However, I just don't get it. How can I get that result? I'm a beginner at java.
First, you need to populate the array with data, and you forgot System.out.println for each row of the array.
int [][] twoD = new int [5][5];
// populate array with data
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = (j+1)*(i+1);
}
}
// print result
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j]);
System.out.print(" ");
}
System.out.println();
}
You have to populate the data as well:
int[][] arr = new int [5][5];
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
arr[i][j] = (j+1)*(i+1);
}
}
And the code to print would be:
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
You are doing fine, you just need to put line jump System.out.println(); every time the second for ends
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You are on the right track, that for loop will print out the array like that, all you need to do is print a new line character after finishing the for(j) loop. But, at least in the snippet you posted, you aren't actually doing any assignments, so there aren't any values in your array to print, Java will initialize all ints to zero for you.
The array doesn't just automatically populate with incrementing integers, rather each cell of the array will automatically initialized to 0, you have to set the values you want the array to contain. You can use the concept of your testing class to do this if you wish, just set each cell of the 2D array to a certain value. After that, you can print out the array, making sure to print a each row of the array on a new line. For instance:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
int increment = 1;
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = increment++;
}
}
for(i = 0; i<5; i++){
for(j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
The first set of nested for loops will set each of the cells of the 2D array to the incremented integers you want (note increment++ will first set the cell to the value increment currently is, then add one to the variable). The second set of nested for loops will print out the array as you desire.
refer this code
int[][] twoD = new int[5][5];
// add values to array
for (int i = 0; i < 5; i++) {
int val = 1;
val = val + i;
for (int j = 0; j < 5; j++) {
twoD[i][j] = val * (j + 1);;
}
}
// Print array
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
as others pointed out you need to print it nicely to see the pattern, i and j are indices of your array. However, I see that you have a nice pattern so just running two loops won't solve the problem.
Maybe something like this would help (not giving exact answer intentionally)
int [][] twoD = new int [5][5];
int i;
// initialize
int c = 1; int j = 0;
for(c=1; c<5; c++) {
for( i = 1; i<=5; i++){
twoD[i-1][c-1] = c*c*i; twoD[c-1][i-1]=c*c*i;
}
}
for( i = 0; i<5; i++) {
for( j = 0; j<5; j++) {
System.out.print(twoD[i][j]);System.out.print(" " );
}
System.out.println("\n");
}

Categories