java performing array calculation [closed] - java

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

Related

How can I print a two-dimensional array of characters in Java, to create a 20x20 grid?

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("]]", ""));
}
}

Array index of bound exception error while traversing a 3* 3 submatrix within a large 7*7 matrix

I want to traverse a 3*3 submatrix within a large 7*7 matrix starting position from (1,1) that is middle element (2nd row , 2nd column).
The corresponding submatrix of position (1,1) will be
[(0,1),(0,2),(0,3)]
[(1,1),(1,2),(1,3)]
[(2,1),(2,2),(2,3)]
Like this traversing will go on.. and next submatrix starting posiion will be (1,2)
[(0,2),(0,3),(0,4)]
[(1,2),(1,3),(1,4)]
[(2,2),(2,3),(2,4)]
My Code
static int i;
static int j;
static int g;
static int h;
static void submatrix(int p,int q,int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(p+","+q);
shiftmatrix(p,q,mat);
}
static void shiftmatrix(int p,int q,int[][] mat) {
int m,n;
int[][] d = new int[3][3];
for( m=0;m<3;m++) {
for( n=0;n<3;n++) {
p=m+(p-1);
q=n+q;
d[m][n]=mat[p][q];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for ( m = 0; m < 3; m++){
for ( n = 0; n < 3; n++){
System.out.print(d[m][n]+"\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = new int[7][7];
int[][] mat = new int[7][7];
for ( i = 0; i < 7; i++)
{
for ( j = 0; j < 7; j++){
Random rand = new Random();
a[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (i = 0; i < 7; i++){
for (j = 0; j < 7; j++){
mat[g][h]=a[i][j];
System.out.print(mat[g][h]+"\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (i=1;i<6;i++) {
for (j=1;j<5;j++) {
int p=i;
int q=j;
submatrix(p,q,mat);
}
}
}
}
while running this code getting error as
ArrayIndexOutOfBoundsException: -1
Please help
The IndexOutOfBoundsException in your code was from you calling p = m + (p - 1). You don't need to change the p and q variables within every iteration of the loop.
In addition, you had several unnecessary variables, and had some of them static, something you should avoid when you're only using them in a loop like this. After cleaning up the code's formatting and deleting all unnecessary variables I believe the code functions as you want it to.
The code ignores the first row and column of your random matrix. Is this desired behavior?
import java.util.Random;
public class MatrixTest {
public static void subMatrix(int startRow, int startCol, int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(startRow + ", " + startCol);
shiftMatrix(startRow, startCol, mat);
}
public static void shiftMatrix(int startRow, int startCol, int[][] mat) {
int[][] d = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//to properly move within the 3x3 you only need to add a
//constant buffer to the indices of mat[][]
d[i][j] = mat[i + startRow][j + startCol];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(d[i][j] + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] mat = new int[7][7];
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++){
Random rand = new Random();
mat[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (int i = 0; i < 7; i++){
for (int j = 0; j < 7; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (int i = 1; i < 5; i++) { //changed from i < 6 to i < 5 to stay inside 7x7
for (int j = 1; j < 5; j++) {
subMatrix(i, j, mat);
}
}
}
}

Printing 2D Array in Java

I'm trying print a 10x10 grid, I don't need any particular symbols, just the 10x10 format. There's actually a lot more to the whole program but right now I'm stuck on this. I really just want to print *'s for a simple Pacman game. I'm not good at programming at all, but I have to pass so I can graduate next semester. Here is what I have so far;
public class Pacman {
public static void main(String[] args) {
int columns = 0;
int rows = 0;
int[][] grid = new int[rows][columns];
for (int i = 0; i < grid.length; i++){
for (int j = 0; j < grid.length; j++){
System.out.println(grid[i][j] + " ");
}
System.out.println();
}
}
}
I don't have errors in syntax or compiling, but nothing actually prints.
int columns = 10;
int rows = 10;
int[][] grid = new int[rows][columns];
for (int i = 0; i < grid.length; i++)
{
for (int j = 0; j < grid.length; j++)
{
grid[i][j] = 0;
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
That will print out a 10x10 with every number in the array being 0
public static void main(String[] args) {
int columns = 10;
int rows = 10;
int[][] grid = new int[rows][columns];
for (int i = 0; i < grid.length; i++){
for (int j = 0; j < grid.length; j++){
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
}

Draw a line in JAVA with Pattern - Beginner

I want to draw a line in java. I will use these draws with making Triangles. I can do this :
1***
11**
111*
1111
and i need to do this:
1***
*1**
**1*
***1
Ive done a lot of work today and my mind got really confused.
Can you help me ? Thanks A lot.
EDIT: also my perfect answer should be Implement Bresenham’s line drawing algorithm but i dont understand in wikipedia.
EDIT 2: my grid code :
String [][] matrix = new String [50][50];
for (int row = 0; row < 50; row++){
for (int column = 0; column < 50; column++){
matrix [row][column] = "*";
}
}
public class Test
{
public static void main(String [] args)
{
int size=50;
String[][] matrix= new String [size][size];
for (int i=0; i < size; i++)
{
for (int j=0; j < size; j++)
{
if (i != j)
matrix[i][j]="*";
else
matrix[i][j]="1";
}
}
for (int i=0; i < size; i++)
{
for (int j=0; j < size; j++)
{
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
}
Edit: if it's already filled with * simply make matrix[i][j]="1"; when i equals j, ie if (i==j).
public class MulArray {
public static void main(String[] args) {
/*
* 1*** 1** 1* 1
*/
String[][] grid = new String[5][5];
for (int row = 0; row < grid.length-1; row++) {
for (int column = 0; column < grid[row].length; column++) {
if (row == column) {
grid[row][column] = "1";
} else {
grid[row][column] = "*";
}
}
}
for (int row = 0; row < grid.length-1; row++)
for (int column = 0; column < grid[row].length; column++) {
if (column != 4) {
System.out.print(grid[row][column]);
}
else{
System.out.print("\n");
}
}
}
}

Add Matrices in Java

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("");}
}

Categories

Resources