Problems getting matrix to display - java

this is my 1st time asking for help for programming. Anywho, I need to write a program which find the determinant of a matrix (The determinant code will be made on a later date). Problem being is that I am having trouble getting my matrix to display. It seems that I have the array written correctly, but the output would skip the for loops to write the matrix. Would there be any changes that needs to be done or if theres a certain way that I need to set my array to determine determinants?
public class DetProg {
public static void main(String[] args) {
Scanner a = new Scanner (System.in);
Random mNum = new Random();
System.out.print("Enter matrix size: ");
int num = a.nextInt();
int numX = num;
int numY = num;
int [][] matNN = new int [numX] [numY];
int det = 0;// 0 is the placeholder until det method is inputted.
int n = mNum.nextInt(100)+1;
if (num >= 2)
{
for(int x = 0; x >= numX; x++)
{
for(int y = 0; y >= numY; y++)
{
matNN [x][y] = n;
System.out.println(matNN[x][y] + " ");
}
}
System.out.println("\n");
System.out.println("Determinant of a matrix is " + det);
}
else
System.out.println("Incorrect matrix size. Exiting...");
}
}

In your loops, you are making mistake in placing condition. you wrote x >= numX and y >= numY which will not be satisfied to even start the loop, because your x and y are equal to 0 in the start. it should be as:
for(int x = 0; x <= numX; x++)
{
for(int y = 0; y <= numY; y++)
{

Firstly you need to change your loop conditions.
for (int x = 0; x < numX; x++) {
for (int y = 0; y < numY; y++) {
this will result in proper assignment of values in an array and after this you can proceed further for your code of Determinant of a matrix.

Related

2D Array with Number Averages

Here is the original question:
Write a program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
I edited the code now to show my new nested for loops at the bottom. These are supposed to compute the average of the entered numbers, however, I am not sure why it does not work?
You can use two variables, one for the row, and one for the column:
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i=0;
int j;
while (i < 3) {
j=0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j]=value;
j++;
}
i++;
}
This logic is weird and never can be met
while (count < 3) {
while (count < 9) {
at the moment that count is bigger than 3 you will never see again the while at count<9
you should think again and reorder the conditional check of that value..
while (count < 9) {
while (count < 3) {
could make more sense...
You could rewrite this segment:
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
...to
double row_sum, value;
double[] row_means;
int row_count = 0, col_count;
while (row_count < 3) {
row_sum = 0.0;
col_count = 0;
while (col_count < 3) {
System.out.print("Enter a number: ");
// TODO: consider adding some input validation
value = scnr.nextDouble();
row_sum += value;
scores[row_count][col_count++] = value;
}
row_means[row_count++] = row_sum / 3.0;
}
... which simultaneously populates your matrix and computes the mean.
Alternatively you can have one loop;
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[count/3][count%3]=value;
count++
}
Think about it in terms of English or pseudo code first, it will be surprisingly easier.
//In English, to get average from 1 row:
/*
1) sum every elements in the row
2) divide sum by number of elements
*/
In codes:
int y = 0;
while(y < col){ //loop through all columns
sum += scores[0][y];
y++;
}
avg = sum / col;
If you can get the average of just one row, congratulations, your work is more than half done. Simply repeat the above process for all other rows with another loop. (This explains why you need 2 loops. One for the columns, the other for the rows).
//In English, to get average from all rows:
/*
1) sum every elements in the row
2) divide sum by number of elements
3) repeat the above till all rows are done
*/
In codes:
int x = 0;
while(x < row){ //loop through all rows
int y = 0;
while(y < col){ //loop through all columns
sum += scores[x][y];
y++;
}
avg[x] = sum / col; //avg needs to be array now, since you need to store 3 values
x++;
}
To get values from row and col:
int row = scores.length;
int col = scores[0].length;

2D array or matrix from int to string in Java

Ok, so i want to create an integer matrix, say with 9 integers some positive and some negative like
int[][] myMatrix = {{1,5,-2},{7,9,3},{-4,-7,6}}
but i want to declare a String matrix of size 3 x 3. then Iterate through the integer matrix and if the current element has a positive integer put the word POSITIVE in the corresponding element in the String matrix, otherwise put NEGATIVE. my code prints fine when i run the matrix for integers but i'm confused how to write the condition for matrix. I already tried googling but nothing. here's my code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class 2D_Matrix {
public static void main(String[] args) throws IOException {
int [][] firstMatrix = {{1, 5, -2},{7, 9, 3},{-4 , -7, 6}};
String[][] secondMatrix = new String[3][3];
for (int x = 0; x < 3; ++x) {
for (int y = 0; y < 3; ++y) {
System.out.print(myMatrix[x][y] + "\t");
}
System.out.println();
}
}
}
i tried many different combinations but nothing works or throws errors. for example:
if(x < 0){
System.out.print("Negative");
}
else if(y < 0){
System.out.print("Negative");
}
else
{System.out.print("positive");
}
but it throws error stating y cannot resolve to a variable. Any help would be much appreciated.
I think what you want is
for (int x = 0; x < 3; ++x) {
for (int y = 0; y < 3; ++y) {
if(firstMatrix[x][y] < 0)
secondMatrix[x][y] = "NEGATIVE";
else
secondMatrix[x][y] = "POSITIVE";
}
}
About your validations
if(x < 0){
}
else if(y < 0){
}
else
{
}
You were validating the index, but index of an array can't be negative. According to your request, you want to validate if the value is negative or positive. Refer to my snippet for how to retrieve value and validate them.

Trying to multiply 2d arrays (like in matrix multiplication), but only works for square matrices

I am a complete Java newbie and I was trying to multiply two 2D arrays like you would multiply two matrices. The program below only works for square matrices, but not for others. I cannot seem to figure out where I am going wrong. If someone could help me out, it would be great.
import java.util.Scanner;
public class TwoDMatrix {
public static void main (String [] args){
Scanner scanme = new Scanner(System.in);
//Input dimensions of Matrix A
System.out.println("Enter the dimensions (row x column) of Matrix A");
int rowA = scanme.nextInt();
int columnA = scanme.nextInt();
int [][] matA = new int [rowA][columnA];
//Input dimensions of Matrix B
System.out.println("Enter the dimensions (row x column) of Matrix B");
int rowB = scanme.nextInt();
int columnB = scanme.nextInt();
int [][] matB = new int [rowB][columnB];
// Declaring new variables
int [][] product = new int [columnA][rowB];
int rowCountA, columnCountA, rowCountB, columnCountB;
int rowCountProduct, columnCountProduct;
int sum;
String divider = "---------";
// Input values of Matrix A
for (rowCountA = 0; rowCountA < rowA; rowCountA++){
for (columnCountA = 0; columnCountA < columnA; columnCountA++){
System.out.printf("%s%d%s%d%s", "Enter the value at A(", rowCountA, ",", columnCountA, ")");
matA[rowCountA][columnCountA] = scanme.nextInt();
}
}
// Input values of Matrix B
for (rowCountB = 0; rowCountB < rowB; rowCountB++){
for (columnCountB = 0; columnCountB < columnB; columnCountB++){
System.out.printf("%s%d%s%d%s", "Enter the value at B(", rowCountB, ",", columnCountB, ")");
matB[rowCountB][columnCountB] = scanme.nextInt();
}
}
//Calculate product of the two matrices
for (rowCountProduct = 0; rowCountProduct < rowA; rowCountProduct++){
for (columnCountProduct = 0; columnCountProduct < columnB; columnCountProduct++){
sum = 0;
for (columnCountA=0, rowCountB=0; columnCountA<columnA && rowCountB<rowB; columnCountA++, rowCountB++){
sum += (matA[rowCountProduct][columnCountA] * matB[rowCountB][columnCountProduct]);
}
product[rowCountProduct][columnCountProduct] = sum;
}
}
//Prints the input matrix A
System.out.printf("%n%s%n%s%n", "Matrix A:", divider);
for (rowCountA = 0; rowCountA < rowA; rowCountA++){
for (columnCountA = 0; columnCountA < columnA; columnCountA++){
System.out.printf("%5d", matA[rowCountA][columnCountA]);
}
System.out.println();
}
//Prints the input matrix B
System.out.printf("%n%s%n%s%n", "Matrix B:", divider);
for (rowCountB = 0; rowCountB< rowB; rowCountB++){
for (columnCountB = 0; columnCountB < columnB; columnCountB++){
System.out.printf("%5d", matB[rowCountB][columnCountB]);
}
System.out.println();
}
//Prints the product
System.out.printf("%n%s%n%s%n", "Product", divider);
for (rowCountProduct = 0; rowCountProduct < rowA; rowCountProduct++){
for (columnCountProduct = 0; columnCountProduct < columnB; columnCountProduct++){
System.out.printf("%5d", product[rowCountProduct][columnCountProduct]);
}
System.out.println();
}
}
}
It has been a while since I learned linear algebra, but I think when you multiply a matrix A[n1][m1] by a matrix B[n2][m2], m1 must be equal to n2 and the result should be a matrix C[n1][m2].
Therefore
int [][] product = new int [columnA][rowB];
should be
int [][] product = new int [rowA][columnB];
And you should verify that columnA == rowB before you start the multiplication.
You have quite a complicated condition here :
for (columnCountA=0, rowCountB=0; columnCountA<columnA && rowCountB<rowB; columnCountA++, rowCountB++){
sum += (matA[rowCountProduct][columnCountA] * matB[rowCountB][columnCountProduct]);
}
Remember the mathematic formula :
be A a n x l matrix, B a l x m matrix, then
forall (i,j) in [1,n]x[1,m], (AB)(i,j) = sum_(k in [1,l]) { A(i,k).B(k,j) }
Therefore, a pseudo-code for this is :
for (int i=0 ; i<A.length ; i++) {
for (int j=0 ; j<B[0].length ; j++) {
prod[i][j] = 0;
for (int k=0 ; k<A[0].length ; k++) {
prod[i][j] += A[i][k]*B[k][j];
}
}
}
Basically, you define your product matrix as:
int [][] product = new int [columnA][rowB];
This means it should have as many rows as there are columns in A, and as many columns as there are rows in B.
But then, when you loop to fill it, this is your loop:
for (rowCountProduct = 0; rowCountProduct < rowA; rowCountProduct++){
for (columnCountProduct = 0; columnCountProduct < columnB; columnCountProduct++){
...
}
}
This means that you're trying to fill the rows in the product, which are supposed to be in the range 0 ≤ rowCountProduct < columnA with values in the range 0 ≤ rowCountProduct < rowA. Similarly, you run the columns to the range columnB instead of rowB as you defined it.
So you should either change the definition of your matrix, or change the way you fill your matrix up.

2D Tiled Game - Using new bad data

In my 2D Tiled game, I have a problem, when I update all the Object from a 2D array in a for loop inside another (looping in the 2D array from top left to bottom right, row by row(like the code below)), If the program is looping at index (5,6) and it need data from the Object under itself, It'll use the new data that he have executed when the loop is at (5,5) but I want to use the all data before the start of the double for loop...
A basical example:
int[][] map = new int[10][10];
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
update(x, y, map);
}
}
// I remember you that it is an example
void update(int x, int y, int[][] m)
{
m[x][y] = 0
if(y > 9) { return; }
m[x][y + 1] = 1
}
It will put instantly the data "1" at (x, 10), without considering that it generate errors...(ArrayOutOfBoundsException...)
How I can make it use the data of the array when he don't started the double loop yet?
I know that it generata ArrayOutOfBoundExecption, and with a single if I can correct it like I done up here
int Water = 1;
int Air = 0;
int[][] map = new int[20][20];
void update()
{
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
tick(x, y, map);
}
}
}
void tick(int x, int y, int[][] m)
{
if(y > m.lenght - 1) { return; }
m[x][y] = Air;
m[x][y + 1] = Water;
}
You are saying that you are iterating your map row by row when you are actually doing it by columns. Try looping first for y and then for x.
Your update method is also wrong. y+1 when y = 9 will try to access map[x][10] which will throw an ArrayOutOfBoundsException. Remember than an array declared as new int[10] has 10 items starting from 0 and ending at position 9.
int Water = 1;
int Air = 0;
int[][] map = new int[20][20];
void update()
{
for(int x = 0; x < 10; x++)
{
for(int y = 9; y >= 0; y--)
{
tick(x, y, map);
}
}
}
void tick(int x, int y, int[][] m)
{
if (y < m[0].length - 1)
m[x][y+1] = m[x][y];
}
Of course, you'll need to make some cells water to begin with, but that should go in the constructor.

how to automatically populate a 2d array with numbers

Hi i am trying to auto populate a 2d array based on user input.
The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array.
for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows.
1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16
But i am struggling to think of the right statement that will do this.
for the moment my code just prints out a 2d array containing *.
Has anyone any ideas how i could print out the numbers , i'm really stuck.
my code follows:
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int num1 = input.nextInt();
int num2 = num1;
int length = num1 * num2;
System.out.println("room "+num1+"x"+num2+"="+length);
int[][] grid = new int[num1][num2];
for(int row=0;row<grid.length;row++){
for(int col=0;col<grid[row].length;col++){
System.out.print("*");
}
System.out.println();
}
}
Read n value,
int[][] arr = new int[n][n];
int inc = 1;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
arr[i][j] = inc++;
Well, first of all you have to fill the array with the numbers. You can use your double for loop for this and a counter variable which you increment after each loop of the inner for loop.
int counter = 1;
for(int x = 0; x < num1; x++)
{
for(int y = 0; y < num2; y++)
{
grid[x][y] = counter++;
}
}
Afterwards you can output the array again with a double for loop.
I am not sure if I understand you right.
You have problem with the code printing *?
If yes, then the reason for that is this
System.out.print("*");
Should be
System.out.print(grid[row]);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int arraySize = input.nextInt();
System.out.println("Length: " + (arraySize*arraySize));
int[][] array = new int[arraySize][arraySize];
int count = 1;
for (int i=0;i<arraySize;i++) {
for (int j=0;j<arraySize;j++) {
array[i][j] = count;
if (j != (arraySize-1))
System.out.print(count + "-");
else
System.out.println(count);
count++;
}
}
}
This code should print out the numbers how you want them.

Categories

Resources