Why aren't the "println" messages printing? - java

I have written this program to create a list, then use the list to populate an array. The method magicCheck then checks to see if the matrix is a magic square. I initially wrote it to be a defined matrix of size 4x4. When I did that, everything worked fine. Now I want to let the user decide the size of the array (nxn). After adding the code to prompt the user for n, and creating the matrix based on nxn rather than 4x4, my printMatrix method has stopped working.
When I run the program as is, and enter n=2, first=2, diff=2, this is the output I get:
"Enter size of array (in form nxn), n:
4
Enter first and diff :
2
2
It is not a magic square."
Can anyone tell me why printMatrix is no longer working? Also, I know that my magicCheck method is sloppy with the loops and I'm sure there are better ways to handle it, but I'm still very new and piecing it together any way I can to get it to work. Please be gentle :]
Here is my code:
import java.util.*;
public class MagicSquare
{
static int row, col, n;
static final int rows = n;
static final int columns = n;
static final int listSize = (n*2);
static Scanner console = new Scanner (System.in);
public static void createArithmeticSeq(int [] list)
{
//prompt user for array size
System.out.println("Enter size of array (in form nxn), n:");
n = console.nextInt();
int first;
int diff;
//prompt user for first and diff
System.out.println("Enter first and diff : ");
first = console.nextInt();
diff = console.nextInt();
//process to create list of 16 elements
for (int i=0; i<listSize; i++)
{
list[i]=first+i*diff;
}
}
public static void matricize (int [] list, int [][] matrix)
{
int i = 0;
//loop through each row
for (row=0; row<matrix.length; row++)
{
//loop through each column
for (col=0; col<matrix[row].length; col++)
{
//populate matrix with values from list
matrix[row][col] = list[i++];
}
}
}
public static void printMatrix(int [][] matrix)
{
for (row=0; row < matrix.length; row++)
{
for (col=0; col < matrix[row].length; col++)
System.out.printf("%2d" + " ", matrix[row][col]);
System.out.println("\n");
}
}
public static void reverseDiagonal(int [] [] matrix)
{
int temp;
for (row=0; row<matrix.length / 2; row++)
{
temp = matrix[row][row];
matrix[row][row] =
matrix[matrix.length - 1 - row] [matrix.length - 1 - row];
matrix[matrix.length - 1 - row][matrix.length - 1 - row] = temp;
}
for (row=0; row<matrix.length / 2; row++)
{
temp = matrix[row][matrix.length - 1 - row];
matrix[row][matrix.length - 1 - row] =
matrix[matrix.length - 1 - row][row];
matrix[matrix.length - 1 - row][row] = temp;
}
}
public static void magicCheck(int [] list, int [] [] matrix)
{
int sum=0, sumRow=0, sumCol=0, sumDiag1=0, sumDiag2=0, magicNumber=0;
for(int i=0; i<listSize; i++)
{
sum += list[i];
magicNumber = sum /= 4;
for(row=0; row<matrix.length; row++)
{
//sum each row, then compare to magicNumber
for(col=0; col<matrix[row].length; col++)
sumRow = sumRow + matrix[row][col];
while (sumRow == magicNumber)
{
for(col=0; col<matrix.length; col++)
{
for(row=0; row<matrix[col].length; row++)
{
sumCol = sumCol + matrix[row][col];
while (sumCol == magicNumber)
{
sumDiag1 = matrix[0][0]+matrix[1][1]+matrix[2][2]+matrix[3][3];
while (sumDiag1 == magicNumber)
{
sumDiag2 = matrix[3][0]+matrix[2][1]+matrix[1][2]
+matrix[0][3];
while(sumDiag2 == magicNumber)
System.out.println("It is a magic square.");
}
}
}
}
}
}
}
System.out.println("It is not a magic square.");
}
public static void main (String [] args)
{
int [] list = new int [listSize];
int [] [] matrix = new int [rows] [columns];
createArithmeticSeq (list);
matricize(list, matrix);
printMatrix(matrix);
System.out.print("\n");
reverseDiagonal(matrix);
printMatrix(matrix);
magicCheck(list, matrix);
}
}

You declare:
static int row, col, n;
static final int rows = n;
static final int columns = n;
static final int listSize = (n*2);
before n is set according to the user-input.
First, remove the final from the declarations.
Second, after you read:
n = console.nextInt();
Do:
rows = n;
columns = n;
...
And last, in your main method, switch the order of the lines:
int [] [] matrix = new int [rows] [columns];
createArithmeticSeq (list);

Related

How to write a method for a transposed matrix?

I am trying to create an application class MatrixApplication, in which the user first enters the number of rows and columns of the matrix.
This will be used to create an array object.
Then the elements of the Matrix are called up row by row and column by column. When all elements have been read in, they are assigned to the matrix object.
Next, the array is transposed and finally the transposed array is displayed.
How do I assign the elements to the Matrix object?
How do I display a transposed array?
package domain;
public class Matrix {
private int[][] numbers;
public Matrix(int rows, int columns) {
setNumbers(numbers);
if (rows < 1)
rows = 1;
else
rows = rows;
if (columns < 1)
columns = 1;
else
columns = columns;
numbers = new int[rows][columns];
}
public final void setNumbers(int[][] numbers) {
this.numbers = numbers;
}
public int[][] getNumbers() {
return numbers;
}
public int[][] transpose() {
int[][] transpose = new int[numbers[0].length][numbers.length];
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < numbers[0].length; ++j) {
transpose[j][i] = numbers[i][j];
}
}
return transpose;
}
}
package ui;
import java.util.Scanner;
import domain.Matrix;
public class MatrixApplication {
public static void main (String[]args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows of the matrix:");
int rows = input.nextInt();
System.out.print("nter the number of columns of the matrix:");
int colums = input.nextInt();
Matrix matrix = new Matrix(rows, colums);
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
}
System.out.printf("The transposed matrix: %d",matrix.transpose());
}
}
And if I want this form of transposed matrix:
example of a 4x2 array to a 2x4 array
Simply read the numbers into a two-dimensional array and call matrix.setNumbers.
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
matrix.setNumbers(numbers);
System.out.printf("The transposed matrix: %s", Arrays.deepToString(matrix.transpose()));

How do I fill a 2D array with random integers [1,9] and print out a 2D array with sums of rows at each row and sum of columns at each column?

The following code is what I have so far, and nothing is working at all. I am intend to Declares a 7×10 two dimensional array in the main. Pass that array to a method which fills the array with random integers [1,9]. Pass the filled array to a method which prints the two dimensional array with the sum of the row at the end of each row and the sum of the column at the end of each column. Row and column labels must also be printed. Any help will be greatly appreciated.
package twodimensionalarray;
import java.util.Arrays;
import java.util.Random;
/**
*
* #author Kristy7
*/
public class TwoDimensionalArray {
//This method is for generating random integers between 1 and 9.
public static int randInt(){
Random rand = new Random();
int randNum;
randNum = rand.nextInt(9)+1;
return randNum;
}
//This method is for filling a 2D array with random integers
public static int[][] fillArray(int[][] toFill){
int[][] toReturn = new int[0][0];
for(int r = 0; r < toFill.length; r++){
for(int c = 0; c < toFill[0].length; c++){
toReturn[toFill[r]][toFill[c]] = randInt(toFill);
}
}
return toReturn;
}
//This method is for for summing rows and columns, and printing rows, columns, the sum of ruws at each row, and the sum of columns at each column.
public static void summingRC(int[][] toSum){
int[] colSums = new int[0];
for(int i = 0; i < toSum.length; i++){
System.out.print(i);
}
System.out.println();
int sum = 0;
for (int r = 0; r < toSum.length; r++) {
for (int c = 0; c < toSum[r].length; c++) {
sum += toSum[c][r];
colSums[c] += toSum[r][c];
}
System.out.println(sum);
}
System.out.println(colSums);
}
/**
* #param args the command line arguments
*
*/
public static void main(String[] args) {
//Declare a 7x10 2D array
int [][] twoDArray = new int[7][10];
//call fillArray method.
int[][] fillingArray = fillArray(twoDArray);
//call SummingRC method
summingRC(fillingArray);
}
}
There's a lot of issues with this code as you are probably aware. Most of them stem from incorrectly instantiating and accessing arrays. I fixed it up:
public static int randInt(){
Random rand = new Random();
int randNum;
randNum = rand.nextInt(9)+1;
return randNum;
}
//This method is for filling a 2D array with random integers
public static int[][] fillArray(int[][] toFill){
int[][] toReturn = new int[toFill.length][toFill[0].length];
for(int r = 0; r < toFill.length; r++){
for(int c = 0; c < toFill[0].length; c++){
toReturn[r][c] = randInt();
}
}
return toReturn;
}
//This method is for for summing rows and columns, and printing rows, columns, the sum of ruws at each row, and the sum of columns at each column.
public static void summingRC(int[][] toSum){
int[] colSum = new int[toSum[0].length];
int[] rowSum = new int[toSum.length];
for(int i = 0; i < toSum.length; i++){
for(int j = 0; j < toSum[i].length; j++){
colSum[j] += toSum[i][j];
rowSum[i] += toSum[i][j];
}
}
System.out.println("Matrix: ");
print2dArray(toSum);
System.out.println("Col sum:");
printArray(colSum);
System.out.println("Row sum:");
printArray(rowSum);
}
/**
* #param args the command line arguments
*
*/
public static void main(String[] args) {
//Declare a 7x10 2D array
int [][] twoDArray = new int[7][10];
//call fillArray method.
int[][] fillingArray = fillArray(twoDArray);
//call SummingRC method
summingRC(fillingArray);
}
public static void print2dArray(int[][] arr){
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void printArray(int arr[]){
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
There's a lot of places where you are instantiating an array with 0 length. Which is basically just a useless array at that point because you can't put any values into it. Ex:
int[] colSums = new int[0];
If you are using Java8. You can do this elegantly by Stream.
Here is the code:
import java.util.Arrays;
import java.util.stream.IntStream;
public class Q47129466 {
public static void main(String[] args) {
int[][] mat = get(5, 5);
System.out.println(Arrays.deepToString(mat));
System.out.println(Arrays.toString(rowSum(mat)));
System.out.println(Arrays.toString(columnSum(mat)));
}
public static int[][] get(int width, int height) {
return IntStream.range(0, height)
.mapToObj(c -> IntStream.range(0, width)
.map(r -> (int) (9 * Math.random() + 1))
.toArray())
.toArray(int[][]::new);
}
public static int[] rowSum(int[][] matrix) {
return Arrays.stream(matrix).mapToInt(row -> IntStream.of(row).sum()).toArray();
}
public static int[] columnSum(int[][] matrix) {
return Arrays.stream(matrix).reduce((a, b) -> add(a, b)).orElse(new int[0]);
}
public static int[] add(int[] a, int[] b) {
int[] sum = new int[Math.max(a.length, b.length)];
for (int i = 0; i < sum.length; i++) {
sum[i] = (i < a.length ? a[i] : 0) + (i < b.length ? b[i] : 0);
}
return sum;
}
}
I think the problem in your code is that you initialized the two dim array in the line int[][] toReturn = new int[0][0];. Here you give the array size and dimension, then in the loop you are trying to populate the array based on the toFill length. Because arrays are fixed in size and do not expand dynamically you can not do this.
Below is the same style code which gots an arrayindexoutofboundsexception. What I suggest to you is that you give the length and dimensions to the method and then initialize the array with these sizes.
The code below is also getting an exception because of the same problem you did which is initializing the array to a size then trying to add elements to it.
public static void main(String[] args) {
int [] [] x =new int[0][0];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
x[i][j]=i+j;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(x[i][j]);
}
}
}

Adding Java 2d Arrays

I need to create a method within my class to add two 2d arrays together. One is implemented as a parameter in the method, while the other is a class object. I need to make sure the arrays are the same size, and if so, add them together. I keep getting an Array Out of Bounds error. Whats wrong with my code?
// method to add matrices
public int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
if (userArray[row][column] == matrix[row][column]) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
if (userArray[row][column] == matrix[row][column]) is the problem.
Remember that arrays are zero-indexed so the elements are numbered from zero to row - 1. Trying to access row row is guaranteed to throw an ArrayIndexOutOfBoundsException because the last row is at index row - 1.
I'm not sure why you even have this line. If you change row to row - 1 and column to column - 1 then this line checks if the bottom-right values in the two matrices are the same. If they're not then the matrices will not be summed. Is that what you intended to do?
I think this is what you are trying to do :
public class Test {
static int row =3;
static int column =2;
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}};
public static void main(String[] args) {
add(new int[][] {{4,4},{5,5},{6,6}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
//check arrays are of the same size
if ((userArray.length == matrix.length) && (userArray[0].length == matrix[0].length) ) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (column -1)) {
for(int col = 0; col < column; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
}
return addedMatrices;
}
}
or better:
public class Test {
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}, {4,4}};
public static void main(String[] args) {
add(new int[][] {{5,5},{6,6},{7,7},{8,8}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
//check arrays are of the same size
if ((userArray.length != matrix.length) || (userArray[0].length != matrix[0].length) ) {
System.out.println("Error: arrays are not of the same size");
return null;
}
int rows = userArray.length;
int cols = userArray[0].length;
int addedMatrices[][] = new int[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (cols -1)) {
for(int col = 0; col < cols; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
return addedMatrices;
}
}
to make the print out more elegant you could change the for loop to :
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
}
System.out.println(Arrays.toString(addedMatrices[i]));
}
The line if (userArray[row][column] == matrix[row][column]) { should be replaced by a line to check if the dimensions of both matrices are the same (I guess that is what's intended). Assuming they are both rectangular arrays, and non empty:
public class MatrixAdder {
static public int[][] userArray = {{1,2},{3,4},{5,6}};
static public int[][] add(int[][] matrix) {
final int nb_rows1 = matrix.length; // nb rows in matrix
final int nb_cols1 = matrix[0].length; // nb columns in matrix
final int nb_rows2 = userArray.length; // nb rows in userArray
final int nb_cols2 = userArray[0].length; // nb columns in userArray
// this assumes A[0] exists, and A[0].length == A[1].length == ...
// both for matrix and userArray
int addedMatrices[][] = new int[nb_rows1][nb_rows1];
if ((nb_rows1==nb_rows2) && (nb_cols1==nb_cols2)) {
for (int i = 0; i < nb_rows1; ++i) {
for (int j = 0; j < nb_cols1; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
static public void main(String[] args)
{
int[][] mx1 = {{10,100},{20,200},{40,400}};
int [][] mx2 = add(mx1);
}
}
To be more robust, you could check that the dimensions of all sub-arrays are the same. You could also check if the matrix has zero dimension (otherwise array[0] will give an error).
If the dimensions are not the same, the returned matrix is filled with zeroes.
If this is not exactly what you need, it should give you enough hints.
if (userArray[row][column] == matrix[row][column]) {}
This is strange to me, I honestly don't know what the intentions are (Your just comparing the last element of each array).
I would do
if(addedMatrices.length == userArray.length && addedMatrices.length == matrix.length){}.
This is ugly but I don't know anything about userArray or matrix. I am presuming userArray is global. Also do j++ and i++, it has the same end result but it is more of the norm.

Adding values on 2d array java

I have created a program that lets the user input the number of rows and columns they want in a 2d array and then it fills the array with all even numbers starting from 0.
I have to add all the numbers in the array to get a total sum and I have no idea how to do that. The rest of my program is complete I'm just having trouble with the sum.
Here is my code:
import java.util.*;
public class ArrayOver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many rows? ");
int x = scan.nextInt();
System.out.println("How many columns? ");
int y = scan.nextInt();
int[][] nums = new int[x][y];
fillArray(nums);
displayArray(nums);
System.out.println();
}
public static void fillArray(int nums[][]) {
int count = 0;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums[0].length ; col++) {
nums[row][col] = count;
count++;
count++;
}
}
}
public static void displayArray(int nums[][]){
for (int row = 0; row < nums.length; row++) {
System.out.println(Arrays.toString(nums[row]));
}
}
}
Try this:
public static void countArray(int[][] nums)
{
int total=0;
for (int row=0;row<nums.length;row++)
for (int col=0;col<nums[0].length;col++)
total += nums[row][col];
System.out.println(total);
}
This should go through all the numbers in the array and add their values to total.
If you want sum all elements of array, just do it:
int sum = 0;
for(int row = 0; row < nums.length ; row++) {
for (int col = 0; col < nums[row].length ; col++) {
sum = sum + nums[row][col];
}
}

trouble with creating a method that returns the average of each column of a 2d array (this is in java)

Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.

Categories

Resources