This question already has answers here:
Converting 1-D String array to 2-D char array
(4 answers)
Closed 9 years ago.
Good day everyone, for the past couple of days I have been working on converting a 1D string array to a 2D char array. My 1D array works fine(zero issues) but when I convert to the 2D char array it only prints out the first row. Below is my code. Any feedback is appreciated. Thanks!
for(int i = 0; i < array1.length; i++) //prints out array
{
System.out.println("1d " + number[i]); //prints the line from the file
}
final int ROWS = 7;
final int COLS = 5;
char[][] 2darray = new char [ROWS][COLS];
for (int i = 0; i < array.length; i++)
{
2darray[i]= array1[i].toCharArray();
}
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
System.out.print(2darray[row][col]);
}
System.out.println();
}
You cannot have variables start with a number in Java. I suggest changing your variables accordingly and trying it out.
char[][] array2 = new char [ROWS][COLS];
for (int i = 0; i < array.length(); i++)
{
array2[i]= array1[i].toCharArray();
}
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
System.out.print(array2[row][col]);
}
System.out.println();
}
See Comments
for(int i = 0; i < array1.length; i++) //prints out array
{
// Why did you use number ?
System.out.println("1d " + array1[i]); //prints the line from the file
}
// You don't need these now.
// final int ROWS = 7;
// final int COLS = 5;
// This will initialize 2darray of size as required according to length of array1
char[][] 2darray = new char [array1.length][];
for (int i = 0; i < array1.length; i++) // What is `array`?
{
2darray[i]= array1[i].toCharArray();
}
for (int row = 0; row < 2darray.length; row++) // Use actual size of 2darray row
{
for (int col = 0; col < 2darray[i].length; col++) // use actual size of 2darray column
{
System.out.print(2darray[row][col]);
}
System.out.println();
}
Related
I am trying to print a 2d array of periods in Java, however, I can not get the formatting correctly. I am able to create a similar layout NOT using a 2d array. However, I will need to be working with a 2d array to finish the project. I have tried using Arrays.deepToString(); but did not find it useful.
My goal is to have a 20x20 grid of periods like this:
** Without the S and the X
My way without using a 2d array:
for (int i = 20; i >= 1; i--) {
for(int j = 1; j <= 20; j++) {
System.out.print(" .");
}
System.out.print("\n");
}
My try using a 2d array:
final int rows = 20;
final int columns = 20;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = ".";
}
System.out.println(Arrays.deepToString(board));
}
Put the two together?...
public static void main(String[] args) {
final int rows = 20;
final int columns = 20;
String board[][] = new String[rows][columns];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = ".";
}
}
display2Darray(board);
}
public static void display2Darray(String[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
System.out.print(arr[row][col]);
}
System.out.println();
}
}
You have to print your 2D array outside outer loop but you print this 2D array result outside inner loop. After that you have to remove bracket and comma through java replace() method.
Here down is modified code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
final int rows = 20;
final int columns = 20;
String board[][] = new String[rows][columns];
// OUTER LOOP
for (int i = 0; i < rows; i++) {
// INNER LOOP
for (int j = 0; j < columns; j++) {
board[i][j] = ".";
}
}
System.out.print(Arrays.deepToString(board).replace("],", "\n")
.replace(",", "")
.replace("[[", " ")
.replace("[", "")
.replace("]]", ""));
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
I'm trying to compute the row and column sums of a 2D array but I'm always getting this error java.lang.ArrayIndexOutOfBoundsException: 2
It says there is a error in method computeRowSums but I cannot figure out why it would be array index out of bounds.
// RowColSums.java
// To compute the row and column sums of a 2D array.
import java.util.*;
public class RowColSums {
public static void main(String[] args) {
int row_size, col_size, row, col;
int[][] array2D;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows and columns: ");
row_size = sc.nextInt();
col_size = sc.nextInt();
array2D = new int[row_size][col_size];
System.out.println("Enter values for 2D array: ");
for(row = 0; row < row_size; row++)
for(col = 0; col < col_size; col++)
array2D[row][col] = sc.nextInt();
int[] rowSums = computeRowSums(array2D);
System.out.print("Row sums: ");
System.out.println(Arrays.toString(rowSums));
int[] colSums = computeColSums(array2D);
System.out.print("Column sums: ");
System.out.println(Arrays.toString(colSums));
}
public static int[] computeRowSums(int[][] arr)
{
int i, j;
int[] row_sum = new int[arr[0].length];
for(i = 0; i < arr[0].length; i++)
for(j = 0; j < arr.length; j++)
row_sum[i] += arr[i][j];
return row_sum;
}
public static int[] computeColSums(int[][] arr)
{
int z, r;
int[] col_sum = new int[arr.length];
for(z = 0; z < arr.length; z++)
for(r = 0; r < arr[0].length; r++)
col_sum[z] += arr[z][r];
return col_sum;
}
}
In computeRowSums you got the indices in the wrong order. It should be :
for(i = 0; i < arr[0].length; i++)
for(j = 0; j < arr.length; j++)
row_sum[i] += arr[j][i];
I'm assuming your 2D array has a different number of rows and columns, which explains the exception you got.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The code below will print two square matrices and I need them to perform multiplication between the two matrices but i cant seem to get that part working. I put a comment right before that block of code where the problem is. But for now all it prints is zeros. Iv been looking online at a lot of sites but cant seem to get mine to work.
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
//create the grid
final int rowWidth = 9;
final int colHeight = 9;
Random rand = new Random();
int [][] board = new int [rowWidth][colHeight];
//fill the grid
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = rand.nextInt(10);
}
}
//display output
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
}
System.out.println();
int [][] board2 = new int [rowWidth][colHeight];
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board[row2].length; col2++) {
board[row2][col2] = rand.nextInt(10);
}
}
//display output
for(int m = 0; m < board2.length; m++) {
for(int n = 0; n < board[m].length; n++) {
System.out.print(board[m][n] + " ");
}
System.out.println();
}
//error is somewhere here
int[][] calculationMultiplication = new int[rowWidth][colHeight];
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] = calculationMultiplication[l][t] + board[l][z] * board2[z][t];
}
}
}
//display output
System.out.println("\nProduct of the 2 matrices is ");
for (int i = 0; i < calculationMultiplication.length; i++) {
for (int j = 0; j < calculationMultiplication[0].length; j++) {
System.out.print(calculationMultiplication[i][j] + " ");
}
System.out.println();
}
} //end of main
} //end of class Main
The problem is that you've not filled the board2 array, so all its elements will be 0. In the for loop, you should also assign random values to board2. You are doing it twice for the board array.
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board2[row2].length; col2++) { // notice 'board2[row].length'
board2[row2][col2] = rand.nextInt(10);
}
}
You should do something similar in the for loops where you display the array:
//display output
for (int m = 0; m < board2.length; m++) {
for (int n = 0; n < board2[m].length; n++) { // notice 'board2[row].length'
System.out.print(board2[m][n] + " ");
}
System.out.println();
}
board2 is always zero.
You fill the wrong array here:
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board[row2].length; col2++) {
board[row2][col2] = rand.nextInt(10);
}
}
Basically you just did simple copy paste mistakes that can be avoidable if you used methods. I'll tell you how but first here's how you can discover your mistake:
System.out.println(String.format("%d * %d = %d",board[l][z], board2[z][t], board[l][z] * board2[z][t]));
Add this just before doing the calculation for calculationMultiplication[l][t]. Try if you want...
Anyway getting back to your mistakes, you have populated your first matrix only, the second one contain zeros (verify your code in the for loop for inserting random numbers into the second matrix), therefore any number multiplied by zero is equal to zero.
I haven't looked at all your code, because it contain a lot of copy paste which confused you and could confuse any one as well, so here's a better way to avoid mistakes in printing the matrix and inserting random numbers:
Printing:
void printMatrix(int[][] matrix){
for(int row =0; row < numOfRows; row++){
for(int col =0; col < numOfCols; col++){
System.out.print(matrix[row][col]+" ");
}
System.out.println(); // new line
}
}
Inserting:
void insertMatrix(int[][] matrix){
for(int row =0; row < numOfRows; row++){
for(int col =0; col < numOfCols; col++){
matrix[row][col] = rand.nextInt(10); // rand must be declared outside any method
}
}
}
Putting all together:
import java.util.*;
public class Main {
// create the grid
final static int rowWidth = 9;
final static int colHeight = 9;
static Random rand;
public static void main(String[] args) {
rand = new Random();
int[][] board = new int[rowWidth][colHeight];
int[][] board2 = new int[rowWidth][colHeight];
int[][] calculationMultiplication = new int[rowWidth][colHeight];
// fill
insertMatrxi(board);
// display output
printMatrix(board);
System.out.println();
// fill
insertMatrxi(board2);
// display output
printMatrix(board2);
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] += board[l][z] * board2[z][t];
}
}
}
// display output
System.out.println("\nProduct of the 2 matrices is ");
printMatrix(calculationMultiplication);
} // end of main
public static void printMatrix(int[][] matrix) {
for (int row = 0; row < rowWidth; row++) {
for (int col = 0; col < colHeight; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println(); // new line
}
}
public static void insertMatrxi(int[][] matrix) {
for (int row = 0; row < rowWidth; row++) {
for (int col = 0; col < colHeight; col++) {
matrix[row][col] = rand.nextInt(10);
}
}
}
} // end of class Main
I need to write a short program on how to add two matrices.. The first matrix should look like this:
1 2 3 4 5 6 7 8 9 10
11 12 13.......19 20
21................30
31................40
41................50
etc..
91...............100
But I don't really come to a solution how to increment the first array.. :S
Here is what I got so far:
package uebung05;
public class MatrixAddition
{
public static void main(String[] argv)
{
int firstArray[][] = new int[10][10];
int secondArray[][] = new int[10][10];
int ergArray[][] = new int[10][10];
System.out.println("Matrix 1\n----------------------------");
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
// Increment Array here???
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nMatrix 2\n----------------------------");
// Dekrementieren der zweiten Matrix
for(int row = 0; row < secondArray.length; row++)
{
for(int column = 0; column < secondArray[row].length; column++)
{
// Array mit Werten befüllen
secondArray[row][column] = column + 1;
System.out.print(secondArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nAddition beider Matrizen\n----------------------------");
// Addition firstArray & secondArray
for(int row = 0; row < ergArray.length; row++)
{
for(int column = 0; column < ergArray[row].length; column++)
{
// Addition
ergArray[row][column] = firstArray[row][column] +
secondArray[row][column];
System.out.print(ergArray[row][column] + " ");
}
System.out.println();
}
}
}
Method to add the first and second matrices together:
public static int[][] matrixAdd(int[][] A, int[][] B)
{
// Check if matrices have contents
if ((A.length < 0) || (A[0].length < 0)) return B;
if ((B.length < 0) || (B[0].length < 0)) return A;
// create new matrix to store added values in
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++)
{
for (int j = 0; j < A[i].length; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
But I don't really come to a solution how to increment the first array.
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
firstArray[row][column] = 1+ row*10 + column;
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
Sum two matrices in the new one and return:
public int[][] addMatrixes(int[][] src1, int[][] src2){
int[][] dst = new int[src1.length][src1[0].length];
for(int i=0;i<src1.length;i++){
for(int j=0;j<src1[0].length;j++){
dst[i][j] = src1[i][j] + src2[i][j];
}
}
return dst;
}
Not very generic, but you can define your first matrix with only one easy loop :
int dim = 10;
int size = dim*dim;
int firstArray[][] = new int[dim][dim];
int row, column;
for (int index = 0; index < size; index++ ){
row = index/dim;
column = index%dim;
firstArray[row][column]=row*10+column+1;
System.out.print(String.valueOf(firstArray[row][column])+"\t");
if (column == 9){ System.out.println("");}
}
I want to read the following into a 2d jagged array:
3
7 4
2 4 6
8 5 9 3
I need to increase the column size on every input. I'm not exactly sure how to do it.
My code is as follows:
int col = 1;
int[][] values = new int[rows][col];
for(int i = 0; i < values.length; i++){
for(int j = 1; j < col; j++)
{
values[i][j] = kb.nextInt();
col++;
}
}
This should do it.
int[][] values = new int[rows][];
for(int i = 0; i < values.length; i++)
{
values[i] = new int[i+1];
for(int j = 0; j < values[i].length; j++)
{
values[i][j] = kb.nextInt();
}
}
Basically, you start by defining how many rows your 2d array should have.
In the for loop, you define the 1d array for each row with its length.
Sample
// don't fix the second dimension
int[][] values = new int[rows][];
for(i = 0; i < rows;i ++){
//column size increases for every line input
values[i] = new int[i+1];
for(j = 0; j < values[i].length; j++) {
values[i][j] = kb.nextInt();
}
}
In Java, arrays do not have to be strictly rectangular. The variable values is a rows-element array of references to int arrays. Here, values[0] is a 1-element int array, values[1] is a 2-element int array, etc.