Java 2D Array: Multiplication Table - java

I'm not sure why my code will not work. Help please! :D
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[r][c];
for (int row = 1; row <= yes.length ; row++)
{
for (int column = 1; column <= yes[row].length; column++)
{
yes[row][column] = (row)*(column);
}
}
return yes;

The index of Array should start 0 rather 1.
Change to the following code and have a try.
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[r][c];
for (int row = 0; row < yes.length ; row++)
{
for (int column = 0; column < yes[row].length; column++)
{
yes[row][column] = (row+1)*(column+1); }
}
return yes;
}
Test code and output in console is as follows:
public class Test1 {
public static void main(String[] args) {
int[][] data = new int[5][5];
data = timesTable(5,5);
for (int row = 0; row < data.length ; row++)
{
for (int column = 0; column < data[row].length; column++)
{
System.out.printf("%2d ",data[row][column]);
}
System.out.println();
}
}
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[r][c];
for (int row = 0; row < yes.length ; row++)
{
for (int column = 0; column < yes[row].length; column++)
{
yes[row][column] = (row+1)*(column+1);
}
}
return yes;
}
}
Output in Console:
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

If you're getting ArrayIndexOutOfBounds its because you are starting from index 1, when it should be 0.
This should do the job:
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[r][c];
for (int row = 1; row <= yes.length ; row++)
{
for (int column = 1; column <= yes[row].length; column++)
{
yes[row-1][column-1] = (row)*(column);
}
}
return yes;
}

int a[][]={{2,3},{3,4}};
int b[][]={{2,3},{3,4}};
int c[][]=new int[2][2];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
c[i][j]=a[i][j]*b[i][j];
System.out.print(c[i][j]+"\t");
}
System.out.println();
}

Related

Matrix in methos

If I have a partially filled 2D matrix from user input, how can I fill it in some other void method to get spiral matrix:
Here is my code: However, when I run it the dimensions of matrix still remain 1000X1000. How can I fix this problem? I need to have only two methods - fillSpiral and main. The program should get any square matrix from user then change its values in a way it becomes a spiral matrix.
import java.util.Scanner;
public class Spiral {
public static void fillSpiral(int matrix[][]) {
int row1 = 0, row2 = matrix.length, col1 = 0, col2 = matrix[0].length;
int num = 1;
while (num <= matrix.length) {
for (int col = col2-1; col >= col1; col--){
matrix[row2-1][col] = num;
num++;
}
for (int row = row2-2; row >= row1; row--) {
matrix[row][col1] = num;
num++;
}
for (int col = col1+1; col < col2; col++) {
matrix[row1][col] = num;
num++;
}
for (int row = row1+1; row < row2-1; row++) {
matrix[row][col2-1] = num;
num++;
}
row1++;
row2--;
col1++;
col2--;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.printf("%12d", matrix[i][j]);
}
System.out.println();
}
}
public static void main(String args[]) {
int n = 0;
int[][] matrixOutput = new int[1000][1000];
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<matrixOutput.length; i++) {
for (int j=0; j<matrixOutput[0].length; j++){
while (keyboard.hasNextInt()) {
matrixOutput[i][j] = keyboard.nextInt();
n++;
}
}
}
fillSpiral(matrixOutput);
}
}
example
Input
1 2 3
4 5 6
7 8 9
Output
5 6 7
4 9 8
3 2 1
Since the algorithm for an spiral matrix is not new i assume your only problem is to read a matrix of an fixed size. Then addressing only your main method use this
//i preferr buffered reader over scanner
try(BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)))
{
ArrayList<String> rows=new ArrayList();
String line=null;
do
{
//example 1,2,3,4,5
System.out.println("Enter an row for this matrix all elements , seperated or an empty string to end input");
line=reader.readLine().trim();
if(!(line.isEmpty() || line.isBlank())){rows.add(line);}
else{line=null;}
}
while(line!=null);
//i assume a square matrix so rows=columns
int n=rows.size();
int[][] matrix=new int[n][n];
for(int i=0;i<n;i++)
{
//split at comma to get columns
String[] columns=rows.get(i).split(",");
//assign each column to the ith row
for(int j=0;j<n;j++){matrix[i][j]=Integer.parseInt(columns[j]);}
}
fillSpiral(matrix);
}

How to append and prepend 2D arrays in Java without Array copy assuming the column sizes are the same?

I've tried following this one How do you append two 2D array in java properly? removing all of the array copys but something is wrong. I also tried another guide but that only worked if the rows were the same.
public int [][] appendMatrix(int[][]matrix, int [][] matrix2)
{
this.matrix = new int[matrix.length + matrix2.length][matrix[0].length];
for(int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix[i].length; j++)
{
this.matrix[i][j] = matrix[i][j];
}
for(int j = matrix.length; j < matrix.length + matrix2.length; j++)
{
this.matrix[i][j]= matrix2[i-matrix.length][j];
}
}
return this.matrix;**
The important thing to consider is when we go from the final row in our first matrix, we want to keep that value so we can use it to add the first through n'th row of our second matrix to our resulting matrix, without losing track.
Example output: output as an array and visualized as a matrix
package matrix;
// I know you don't want to use imports, this is simply for testing purposes.
import java.util.Arrays;
public class MatrixAddition
{
public static void main(String[] args)
{
int[][] matrix1 =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 } };
int[][] matrix2 =
{
{ 1, 1, 1 },
{ 2, 3, 4 } };
System.out.println("Appending the two matrices results in: ");
System.out.println(Arrays.deepToString(twoDMatrixAppend(matrix1, matrix2)));
printMatrix(twoDMatrixAppend(matrix1, matrix2));
System.out.println("\nPrepending the two matrices results in: ");
System.out.println(Arrays.deepToString(twoDMatrixPrepend(matrix1, matrix2)));
printMatrix(twoDMatrixPrepend(matrix1, matrix2));
}
private static int[][] twoDMatrixAppend(int[][] matrix1, int[][] matrix2)
{
if (matrix1[0].length != matrix2[0].length)
{
return null; // Or throw new incompatible matrices exception
}
int resultingRowLength = matrix1.length + matrix2.length; // The new length of the resulting matrix
int[][] result = new int[resultingRowLength][matrix1[0].length];
int currentRow, col, matrixTwoRowStart;
for (currentRow = 0; currentRow < matrix1.length; currentRow++)
{
for (col = 0; col < matrix1[0].length; col++)
{
result[currentRow][col] = matrix1[currentRow][col];
}
}
for (matrixTwoRowStart = 0; matrixTwoRowStart < matrix2.length; matrixTwoRowStart++, currentRow++)
{
for (col = 0; col < matrix2[0].length; col++)
{
result[currentRow][col] = matrix2[matrixTwoRowStart][col];
}
}
return result;
}
private static int[][] twoDMatrixPrepend(int[][] matrix1, int[][] matrix2)
{
return twoDMatrixAppend(matrix2, matrix1);
}
private static void printMatrix(int[][] arr)
{
System.out.println();
int row, col;
for (row = 0; row < arr.length; row++)
{
for (col = 0; col < arr[0].length; col++)
{
System.out.print(String.format("%4d", arr[row][col]));
}
System.out.println();
}
}
}

Separate methods for matrix and swapping diagonals

I am supposed to create a matrix and split it into 3 methods, where first one will read matrix, second will print matrix and third one will swap diagonals. Read matrix works but I've tried to pass the parameters to other methods so they can work too but when I call them in main class, it doesn't work.
public static void readMatrix() {
Random rand = new Random();
Scanner in = new Scanner(System.in);
System.out.println("Please insert how many rows and columns you want for matrix");
int ColumnsAndRows = in.nextInt();
int matrix[][] = new int[ColumnsAndRows][ColumnsAndRows];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = rand.nextInt(ColumnsAndRows * ColumnsAndRows) + 1;
}
}
}
public int[][] printMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
return matrix;
}
public int[][] swapDiagonals(int ColumnsAndRows, int matrix[][]) {
for (int i = 0; i < ColumnsAndRows; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][ColumnsAndRows - i - 1];
matrix[i][ColumnsAndRows - i - 1] = temp;
}
printMatrix(matrix);
return matrix;
You can use an int[][] store the matrix returned from readMatrix.
It is redundant here to let printMatrix and swapDiagonals return int[][].
You can let printMatrix and swapDiagonals be static, so you can call them in main method.
Here is a sample:
public class Matrix {
public static int[][] readMatrix() {
Random rand = new Random();
Scanner in = new Scanner(System.in);
System.out.println("Please insert how many rows and columns you want for matrix");
int ColumnsAndRows = in.nextInt();
int matrix[][] = new int[ColumnsAndRows][ColumnsAndRows];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = rand.nextInt(ColumnsAndRows * ColumnsAndRows) + 1;
}
}
return matrix;
}
public static void printMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
}
public static void swapDiagonals(int matrix[][]) {
int ColumnsAndRows = matrix.length;
for (int i = 0; i < ColumnsAndRows; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][ColumnsAndRows - i - 1];
matrix[i][ColumnsAndRows - i - 1] = temp;
}
printMatrix(matrix);
}
public static void main(String[] args) {
int[][] matrix = readMatrix();
printMatrix(matrix);
System.out.println("swapDiagonals:");
swapDiagonals(matrix);
}
}
Result:
Please insert how many rows and columns you want for matrix
4
12 10 14 5
14 8 9 13
2 15 5 16
11 9 8 10
swapDiagonals:
5 10 14 12
14 9 8 13
2 5 15 16
10 9 8 11

Multiplication table with 2d array

I need to make a multiplication table that shows 1 * 1 up to 12 * 12. I have this working but it needs to be in 13 columns in a format that looks like the diagram below, really appreciate any help.
1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 ...
2 2 4 6 8 10 ....
3
4
5
6
...
Code so far:
public class timetable {
public static void main(String[] args) {
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = (row+1) * (col+1);
}
}
for (int row = 0; row < table.length; row++) {
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
}
}
Print column headings before printing the table, and print row headings at the start of each row. You can use the code below.
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = (row+1) * (col+1);
}
}
// Print column headings
System.out.printf("%6s", "");
for (int col = 0; col < table[0].length; col++) {
System.out.printf("%6d", col+1);
}
System.out.println();
for (int row = 0; row < table.length; row++) {
// Print row headings
System.out.printf("%6d", row+1);
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
This only prints 9x9 timetable, if you need to change it 12x12, then just change the numbers in the code from "9" to "12", and add more "----" lines in the system output to match it
This includes " * |" and "----" ...
Thought this might be helpful for anyone else
Output:
9x9 Timetable
public class timetable2DArray
{
public static void main(String[] args)
{
int[][] table = new int[9][9];
for (int row=0; row<9; row++)
{
for (int col=0; col<9; col++)
{
table[row][col] = (row+1) * (col+1);
}
}
// Print column headings
System.out.print(" * |");
for (int col = 0; col < table[0].length; col++)
{
System.out.printf("%4d", col+1);
}
System.out.println("");
System.out.println("------------------------------------------");
for (int row = 0; row < table.length; row++)
{
// Print row headings
System.out.printf("%4d |", row+1);
for (int col = 0; col < table[row].length; col++)
{
System.out.printf("%4d", table[row][col]);
}
System.out.println();
}
}
}
int [][] A = new int[5][5];
int [][] B = new int[5][5];
for (int row = 0; row < A.length; row++) {
System.out.println();
for (int col = 0; col < A.length; col++) {
B[row][col] = (row+1)*(col+1);
System.out.print("\t");
System.out.printf("%2d", B[row][col]);
}
}
You could implement a timesTable() method. Here's my code, modify it anyway you would like.
//main driver
public static void main(String[] args) {
int[][] data; //declaration
data = timesTable(4,6); //initialisation
for (int row = 0; row < data.length ; row++)
{
for (int column = 0; column < data[row].length; column++)
{
System.out.printf("%2d ",data[row][column]);
}
System.out.println();
}
}
//method
public static int[][] timesTable(int r, int c)
{
int [][] arr = new int[r][c];
for (int row = 0; row < arr.length ; row++)
{
for (int column = 0; column < arr[row].length; column++)
{
arr[row][column] = (row+1)*(column+1);
}
}
return arr;
}

Top to bottom for numbered triangle [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Below I had tried to come up with a method to find the path to figure out the shortest path but every time I run the program I get a nullpointer exception at the findshortestPath1 at the int cols = myArray[rows].length I don't know how to solve this problem. If you have other methods I can try to solve this, tha twill be greatly appreciated.
*******UPDATE******* Okay I updated that code with your suggestions, but I was still getting problems at
minCosts[0] = myArray[row][col]
and
findShortestPath(myArray, minCosts, row, col);
Code:
import java.util.Random;
public class Triangle{
public static void createTriangle(int numRows){
int rows=numRows;
int max =9, min =2;
int[][] myArray = new int[rows][];
Random random = new Random();
for (int i = 0; i < rows; i++) {
myArray[i]= new int[i+1];
//Below is used for organizing the triangle
System.out.println("");
for(int p=rows-i; p>0;p--)
System.out.print(" ");
for (int j = 0; j <=i; j++) {
//below puts the spacing between each column in the triangle
System.out.print(" ");
myArray[i][j] = random.nextInt(max - min + 1) + min;
System.out.print(myArray[i][j]);
System.out.print(" ("+i+", "+j+") ");
}
}
}
public static int findShortestPath1(int numRows) {
int rows= numRows;
int[][] myArray = new int[rows][];
int numNodes = sumToN(rows);
int[] minCosts = new int[numNodes];
for(int row = 0; row<rows; row++) {
int cols = new int[rows].length;
for(int col = 0; col< cols; col++) {
findShortestPath(myArray, minCosts, row, col);
}
}
int row = rows;
int cols = new int[rows].length;
int min1 = -1;
for(int col = 0; col<cols; col++) {
int cost = minCosts[indexFromRowCol(rows,col)];
if(cost < min1 || min1 ==-1) {
min1 = cost;
}
}
return Math.max(0, min1);
}
private static int findShortestPath(int[][] myArray, int[] minCosts, int row, int col) {
if (row == 0) {
minCosts[0] = myArray[row][col];
return minCosts[0];
}
int minValue = -1;
if (col - 1 >= 0) {
minValue = minCosts[indexFromRowCol(row - 1, col - 1)];
}
if (col < myArray[row - 1].length) {
int cost = minCosts[indexFromRowCol(row - 1, col)];
if (minValue == -1) {
minValue = cost;
}
minValue = Math.min(minValue, cost);
}
int minCost = myArray[row][col] + minValue;
minCosts[indexFromRowCol(row, col)] = minCost;
return minCost;
}
private static int sumToN(int n) {
if (n < 0) {
return 0;
}
return n * (n + 1) / 2;
}
private static int indexFromRowCol(int row, int col) {
return sumToN(row) + col;
}
}
This:
for(int row = 0; row >= rows; row++)
Should be:
for(int row = 0; row < rows; row++)
Suppose, for example, that rows = 10. Then row >= rows is equivalent to 0 >= 10, which is false, so the for loop never runs.
When you do:
int row = rows - 1;
int cols = myArray[row].length;
You will get row = 9 but, since the for loop didn't execute, myArray is still empty. So you get a NullPointerException when you try to access myArray[9].length.
Another problem is that, since you did not initialize the size of the second dimension when you did:
int[][] myArray = new int[rows][];
You will still get a NullPointerException inside the for loop when you try to do:
int cols = myArray[row].length;
So you probably want to initialize myArray in findShortestPath1() the same way you did in createTriangle().

Categories