How do you print rows and columns in a 2-d array? - java

I'm trying to get this array to display 4 values arranged in a 2x2 array. With what I'm doing so far, I'm getting an array out of bounds error. How can I do this display properly?
import java.util.Scanner;
import java.util.Random;
public class GridPractice
{
public static void main(String[] args)
{
//declarations
Scanner in = new Scanner(System.in);
Random generator = new Random();
int [][] grid; //un-instantiated grid
int size = 0; //number of rows and columns
//get size of grid - no validation & instantiate
System.out.print("Enter size of grid: ");
size = in.nextInt();
grid = new int[size][size];
//fill grid with random number from 1..99
System.out.println();
for (int row=0; row<size; row++)
{
for (int col=0; col<size; col++)
{
grid[row][col] = generator.nextInt(100); //random numbers 0.99 - not 100
}
}
System.out.printf("%2d\n", grid[size][size]);

for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
System.out.printf("%2d ", grid[row][col]);
}
System.out.println();
}

Try this:
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println("");
}
plus remove this line, this is the culprit of the exception:
System.out.printf("%2d\n", grid[size][size]);

Related

How do I randomly pick an element from an array in Java? [duplicate]

This question already has answers here:
How to randomly pick an element from an array
(13 answers)
Closed 5 months ago.
The title sounds simple but it's a bit more complicated. This is for an entry level Java class so excuse the lack of use of methods and whatnot!
Essentially, we want the user to create the size of their array, and then print out a random assortment of either spaces or blocks. This is what I have so far.
What I don't know how to do is print out either the space or the block according to the user-determined size of the array. Any help is appreciated!
import java.util.Scanner;
import java.util.Random;
public class ArtLab {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the 2D art generator!");
System.out.println("Lets define the size of your canvas.");
System.out.println("Please enter your x:");
int x = input.nextInt();
System.out.println("Please enter your y:");
int y = input.nextInt();
input.nextLine();
char[][] canvasSize = new char[x][y];
for (int row = 0; row < x; row++)
{
for (int col = 0; col < y; col++)
{
canvasSize[row][col] = ' ';
}
}
for (int row = 0; row < x; row++)
{
for (int col = 0; col < y; col++)
{
canvasSize[row][col] = '█';
}
}
for(int row = 0; row < x; row++)
{
for(int col = 0; col < y; col++)
{
System.out.print(canvasSize[row][col]);
}
System.out.println();
}
if(x <= 0 || y <= 0)
{
System.out.println("Invalid input!");
System.exit(0);
}
}
}
Initialize the array like this:
for (int row = 0; row < x; row++)
{
for (int col = 0; col < y; col++)
{
canvasSize[row][col] = Math.random()>0.5 ?' ':'█';
}
}

Trying to input values into a 2d array and print it, code not running

Code not running??
import java.util.Scanner;
public class Array2dNightPractice
{
int[][] studentmarks;
studentmarks = new int[3][3];
Scanner kb = new Scanner(System.in);
System.out.println("Enter 9 integers");
for(int row = 0;row<3;row++){
for(int col=0;col<3;col++){
studentmarks[row][col] = kb.nextInt();
}
}
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 4; col++) {
System.out.print(studentmarks[row][col] + " ");
}
System.out.println();
}
}
you're getting IndexOutOfBoundsException because of this --> col < 4.
for(int col = 0; col < 4; col++)
change to this:
for(int col = 0; col < studentmarks[row].length; col++)
side note - make use of the length property to prevent errors such as the one you've just encountered.
full solution:
for(int row = 0; row < studentmarks.length; row++) {
for(int col = 0; col < studentmarks[row].length; col++) {
System.out.print(studentmarks[row][col] + " ");
}
System.out.println();
}
the error comes from exceeding the bound of the array studentMarks in the second for loops at the number 4 it should be 3
A good habit to develop is to create constant variables as required with the size of each of the rows and columns, so you will not fall in such mistake.
Something like this:
import java.util.Scanner;
public class Array2dNightPractice{
public static void main(String[] agrs){
final int ROW =3, COL=3; // constant variable to determine the size of the 2d array
int[][] studentMarks = new int[ROW][COL];
Scanner in = new Scanner(System.in);
System.out.println("Enter 9 integers");
for(int row = 0;row<ROW;row++){ //note how I don't need to memorize and rewrite the numbers every time
for(int col=0;col<COL;col++){
studentMarks[row][col] = in.nextInt();
}
}
// print the marks as matrix
for(int row =0; row <ROW; row++) {
for(int col =0; col <COL; col++) {
System.out.print(studentMarks[row][col] + " ");
}
System.out.println();
}
}
}

Finding the location of a number in a 2d array

I am trying to create a program that lets you find how many times a curtain number occurs in a 2d array. One of the things that I am required to do is to create a method called countInstence which counts the amount of times a number occurs but also where they are located in the array. the problem i'm having is how do I output the location of the the number
public int[][] createArray(int rSize, int cSize) {
Random rnd = new Random();
int[][] array = new int[rSize][cSize];
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
array[row][col] = rnd.nextInt(26);
}
}
return array;
}
public void print2dArray(int[][] array) {
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
System.out.print(array[row][col] + "\t");
}
System.out.println("\n");
}
}
public int countInstence(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search)
count++;
}
}
return count;
}
public static void main(String[] args) {
Journal5b call = new Journal5b();
Scanner in = new Scanner(System.in);
int[][] myArray;
int value;
myArray = call.createArray(10, 10);
call.print2dArray(myArray);
System.out.println("Enter a number to search for: ");
value = in.nextInt();
System.out.println("Your number occurred "
+ call.countInstence(myArray, value) + " Times");
}
Just insert a one line print statement inside of the if-statement and format to print the row and column of the current index, as below...
public int countInstance(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search) {
System.out.printf("Instance found at [%d, %d]\n", row, col);
count++;
}
}
}
return count;
}
If you aren't familiar with the System.out.printf call or the %d symbols, you can read more about it here.
Just add this line to the for loop
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search) {
System.out.printf("Instance found at [%d, %d]\n", row, col);// add this line
count++;
}
}
}
If you want to also use location at other place then just declare a List and add location to that list while searching for element.
public static List<String> location=new ArrayList<String>();
public int countInstence(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search)
{
count++;
String loc=row+","+col;
location.add(loc);
}
}
}
return count;
}
public static void main(String[] args) {
Test call = new Test();
Scanner in = new Scanner(System.in);
int[][] myArray;
int value;
myArray = call.createArray(10, 10);
call.print2dArray(myArray);
System.out.println("Enter a number to search for: ");
value = in.nextInt();
System.out.println("Your number occurred "
+ call.countInstence(myArray, value) + " Times");
System.out.println("locations :");
for(int i = 0; i < location.size(); i++) {
System.out.println(location.get(i));
}
}
I suggest using Points:
List<Point> locations=new ArrayList<Point>();
....
if (array[row][col] == search)
{
count++;
locations.add(new Point(row,col));
}

Add the individual columns and rows in a 2D Array and display in a 1D Array table?

I'm a beginner in Java programming. I have created the 2D array that generates random numbers to fill the array.
But now I need to calculate the sum of the rows and columns individually and store the values in a separate table formatted in a 1D array using a method...
This is what I have so far:
import java.util.*;
import java.math.*;
public class Q42 {
public static void main(String[] args) {
//create the grid
final int rowWidth = 4;
final int colHeight = 5;
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();
} //end of main
public static int[] sumTableRows(int[][] table)
{
int rows = table.length;
int cols = table[0].length;
int[] sum = new int[rows];
for(int x=0; x<rows; x++)
for(int y=0; y<cols; y++)
sum[x] += table[x][y];
return sum;
}
} //end of class Main
So if i understand you correctly, this is what you want to do:
You have a 2D array with random values. you want to sum up all the values in every row and put in a variable. Easy. This is how you do it:
public static int[] sumTableRows(int[][] table)
{
int rows = table.length;
int cols = table[0].length;
int[] sum = new int[rows];//make an array for sums
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++){//iterate over all vars in the table array
int temp = table[i][j];//take value in point (i,j)
sum[i] += temp;//sum it in sum[i].
}
}
return sum; //return the 1D array
}

java performing array calculation [closed]

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

Categories

Resources