I have a question regarding Java code implementation for the following scenario,
What I have done is as follows,
charArray has been created as a 6 by 6 array. char[][] charArray = new char[6][6];
Scanner scn = new Scanner (System.in);
System.out.print("String text: "); //Text from user
String str= scn.nextLine();
str = str.replaceAll("\\s+","");
char[] cArray = text.toCharArray(); //Convert String to char array
for (int i = 0; i < cArray.length; i++)
{
for (int row = 0; row < charArray.length; row++)
{
for (int col = 0; col < charArray[row].length; col++)
{
System.out.println("i = " + i);
//charArray[row][col] = letters[i]; //I'm supposed to put in the converted String to char and put into the 2D Array of 6 by 6. When I executed the script, there is an array out of bound exception
System.out.println("charArray[" + row + "]" + "[" + col + "]" + "cArray[" + i + "]");
++i;
System.out.println("End of col for loop");
}
System.out.println("End of row for loop");
}
i = i;
}
System.out.println("End of i for loop");
It seems from the printing of messages, I could get the text's i position and to it's corresponding 2D array positions. But I could not populate the values by assigning.
I appreciate any tips and guidance for the above case.
Thank you very much.
I didn't get your question. But if you want to store in 6*6 character array without getting exception. Here is the code how to do it
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
sc.close();
s=s.replaceAll("\\s+", "");
char []ch = s.toCharArray();
char [][]charArray = new char[6][6];
int i=0, j=0;
for(int k=0;k<ch.length;k++)
{
if(i<=5 && j<=5)charArray[i][j] = ch[k];
j++;
if(j>5) {
j=0;
i++;
}
if(i>5 && j>5) break;
}
The easiest way is to make sure the user has entered 36 characters exactly, then you can just copy the char array.
Scanner scn = new Scanner (System.in);
System.out.print("String text: ");
String str = "";
// Read 6x6 characters
while (str.toCharArray().length != 36)
{
System.out.print("Enter 36 characters: ");
str = scn.nextLine().replaceAll("\\s+","");
}
char[] cArr = str.toCharArray();
// Print in 6x6 grid
for(int i=0; i<36; i++)
{
System.out.print((i%6==0?"\n ":" ")+cArr[i]);
}
System.out.println();
And you could use that 1D array as a flat 2D array, or parse them into a 2D array in this way.
System.out.println("-------------------");
char[][] cMat = new char[6][6];
// Parse it into 6x6 matrix
for(int i=0; i<36; i++)
{
cMat[i/6][i%6] = cArr[i];
}
// Print 6x6 matrix
for(int i=0; i<6; i++)
{
for(int j=0; j<6; j++)
{
System.out.print(" "+cMat[i][j]);
}
System.out.println();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.