Out of Bounds Error in 2D Array with Dice Program - java

So I am creating a program that rolls z die x times with y sides, and I keep getting an out of bounds error at the first line in the first for loop. However I'm not sure why this is, the loop counts from 0 to (z-1). I'm basically in the home stretch of this program and I need the help of the stackoverflow community.
public class Ass11f {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter how many times you want to roll the die: ");
int x = console.readInt();
System.out.print("Enter the amount of sides: ");
int y = console.readInt();
System.out.print("Enter the amount of die: ");
int z = console.readInt();
int[][] dice = new int[x][z];
int row = 0;
for (int i = 0; i<z; ++i){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x)) {
i = 0;
++row;
}
}
row = 0;
int[] sum = new int[x];
for (int j = 0; j<z; ++j){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x)) {
j = 0;
++row;
}
}
int[] counter = new int[2*y];
int k = 0;
while (k<sum.length){
for (int l = 0;l<((2*y)-1);++l){
if (sum[k]==l) ++counter[l];
if (l==((2*y)-1)) {
++k;
}
}
}
for (int m = 0;m<sum.length;++m) System.out.println(sum[m]+"'s: "+counter[m]+"times, "+((((double)counter[m])/x)*100)+"%");
}
}

first loop:
for (int i = 0; i<z; i++){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x-1)) {
i = -1;
++row;
}
}
second loop:
for (int j = 0; j<z; j++){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x-1)) {
j = -1;
++row;
}
}
Third loop: runs forever. I'm not sure what this is trying to achieve, so I can't fix it for you...

There are x rows but you are using z as the row loop
int[][] dice = new int[x][z]; <-- x is the row count
int row = 0;
for (int i = 0; i < z; ++i){ <--- The outer loop is iterating the rows (x),
Here's how to iterate through a 2D array
int[][] dice = new int[x][z];
for (int i = 0; i < x; i++){
for (int j = 0; j < z; j++){
// do something with dice[i][j]
}
}

Related

How to create a method in java which prints out the elements of a matrix in shown pattern?

The contents of the matrix starts from 1 to the product of rows and columns. The method "scan" should print out as per following:
If the row is entered 4 and column is entered 7, the contents of the matrix should look like the image provided here:
the correct matrix
So far I have tried absolutely noting because I just don't know how to make this possible. I can print in zigzag, spiral but I just have no idea about this one. Please have mercy on me and grant me an insight.
This code currently prints out in a spiral pattern.
How should I modify this "scan" method so it satisfies the aforementioned condition?
import java.util.Scanner;
import java.util.Random;
public class that {
public static void main(String[] args) {
int range;
range = 100;
Scanner scn = new Scanner(System.in);
while(true) {
int m, n;
System.out.println("Enter the number of row: ");
m = scn.nextInt();
System.out.println("Enter the number of column: ");
n = scn.nextInt();
if(m <= 0||n <= 0) break;
int[][] tab = new int[m][n];
generate(tab, range);
scan(tab);
}
scn.close();
}
static int len(int x) { return (""+x).length(); }
static void generate(int[][] tab, int range) {
// Random generation
Random rg = new Random();
for(int i=0; i<tab.length; ++i)
for(int j=0; j<tab[0].length; ++j)
tab[i][j] = rg.nextInt(2*range) - range;
}
static void scan(int[][] tab) {
int m = tab.length;
int n = tab[0].length;
int totalWidth = 0;
int num = 1;
int rowStart = m - 1, rowEnd = 0, colStart = 0, colEnd = n - 1;
// Compute column widths
int[] colw = new int[n];
for(int j=0; j<n; ++j) { // For every column look down
colw[j] = len(j); // (""+j).length();
for(int i=0; i<m; ++i) {
int w = len(tab[i][j]); //("" + tab[i][j]).length();
if(w > colw[j]) colw[j] = w;
}
totalWidth += colw[j];
}
// Printing
int ris = len(m-1); // row index size
System.out.printf("%"+ris+"s ", " ");
for(int j=0; j<n; ++j)
System.out.printf("%" + colw[j] +"d ", j);
System.out.println();
System.out.printf("%"+ris+"s+"," ");
for(int j=0; j<totalWidth+n-1; ++j)
System.out.printf("-");
System.out.println();
while (rowStart >= rowEnd && colStart <= colEnd) {
// Print leftmost column from bottom to top
if (colStart <= colEnd) {
for (int i = rowStart; i >= rowEnd; i--) {
tab[i][colStart] = num++;
}
colStart++;
}
// Print top row from right to left
if (rowStart >= rowEnd) {
for (int i = colStart; i <= colEnd; i++) {
tab[rowEnd][i] = num++;
}
rowEnd++;
}
// Print rightmost column from top to bottom
if (colStart <= colEnd) {
for (int i = rowEnd; i <= rowStart; i++) {
tab[i][colEnd] = num++;
}
colEnd--;
}
// Print bottom row from left to right
if (rowStart >= rowEnd) {
for (int i = colEnd; i >= colStart; i--) {
tab[rowStart][i] = num++;
}
rowStart--;
}
}
// Prints the matrix
for(int i=0; i<m; ++i) {
System.out.printf("%"+ris+"d|", i);
for(int j=0; j<n; ++j)
System.out.printf("%" + colw[j] +"d ", tab[i][j]);
System.out.println();
}
System.out.println();
}
}

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

Homework assignment to fill mock array with random values

How can I create xy matrix (where x <= y) with random integers (from 0 to 9) which has at least x zeros and max (xy)/2 in java?
Size of matrix (x,y) is given. Also I would like to know how to use this matrix with same integers with same index in other class (for example 'public class Game{...}'). I'm a beginner so please make it easy for me :)
My code so far:
import java.util.Random;
public class Solution {
int a[][];
public void P(int x, int y){
Random r = new Random();
a = new int[x][y];
for (int i=0; i<x; i++){
for (int j=0; j<y; j++){
a[i][j] = r.nextInt(10);
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println();
int zeros = 0;
for (int i=0; i<x; i++){
for (int j=0; j<y; j++){
if(a[i][j]==0){
zeros ++;
}
}
}
System.out.println(zeros);
}
public int[][] getA() {
return a;
}
}
Random r = new Random();
a = new int[x][y];
int noZeros = r.nextInt((y*x)/2-x) + x;
boolean z[][] = new boolean[x][y];
for (int i = 0; i < noZeros; i++) {
z[r.nextInt(x)][r.nextInt(y)] = true;
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (!z[i][j]) {
a[i][j] = r.nextInt(9) + 1;
}
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println();
int zeros = 0;
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (a[i][j] == 0) {
zeros++;
}
}
}
System.out.println(zeros);
In my solution I create first boolean matrix, which represents zeros, then I chose random number, but from 1 to 9.
I would first determine how many 0s you will have in the matrix, getting a random int from within your min/max bound. Then I would calculate the other xy - numZeros random integers. Finally, for each cell in the matrix, I would pick a random element from a combined list (your 0s + other random integers, removing the element when it is picked).

Making Tree with Nested Loops

So, for my programming class, our teacher tasked us with making a tree out of *'s and other random characters. There has to be a star at the top of the tree that increases in size every so often, depending how large the user wants the tree. For some reason, if the number the user enters is greater than 15, the bottom half is too far to the right. I tried changing my code, but then everything less than 15 is too far the right. How can I get that to work?
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int a = scan.nextInt();
int b = 0;
int c = 0;
int d = 0;
if ( a >= 12){
d = 1;
} else {
d = 0;
}
//Top Half of Star
for (int i = 0; i < a / 4; i++) {
for (int j = i; j < a; j++){
System.out.print(" ");
}
for (int j = 0; j < 2 * i + 1; j++){
System.out.print("*");
b = b + 1;
}
System.out.println("");
}
//Bottom Half of Star
for (int i = 1; i < a/4; i++){
for (int j = d; j < a; j++){
System.out.print(" ");
}
for (int j = c; j < b/3; j++){
System.out.print("*");
}
c = c + 2;
d = d - 1;
System.out.println("");
I think this is what you're looking for, if you're defining the size as the number of rows.
import java.util.Scanner;
public class NestedTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int size = scan.nextInt(); // Get the size of the tree
for (int i = 0; i < size; i++) {
int spaces = size - i;
for (int s = 0; s < spaces; s++) { // Print spaces
System.out.print(" ");
}
for (int r = 0; r <= i; r++) { // Print stars
System.out.print("* ");
}
System.out.print("\n"); // new line
}
}
}

How do i complete this question with 2-dimensional array in java?

Hey guys, im working through the Introduction to Programming in Java book and one of the exercises is this:
Empirical shuffle check. Run
computational experiments to check
that our shuffling code works as
advertised. Write a program
ShuffleTest that takes command-line
arguments M and N, does N shuffles of
an array of size M that is initialized
with a[i] = i before each shuffle, and
prints an M-by-M table such that row i
gives the number of times i wound up
in position j for all j. All entries
in the array should be close to N/M.
Now, this code just outputs a block of zeros...
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
for (int i = 0; i < M; ++i)
deck [i] = i;
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
for(int n = 0; n < N; n++) {
int r = i + (int)(Math.random() * (M-i));
int t = deck[r];
deck[r] = deck[i];
deck[i] = t;
for (int b = 0; b < N; b++)
{
for (int c = 0; c < M; c++)
System.out.print(" " + a[b][c]);
System.out.println();
}
}
}
}
}
}
What am i doing wrong? :(
Thanks
So a is like a history? As you are now it is always filled with zeroes just like you initialized, you never assign to it! After the "shuffling" for loop you need to set
A[i][POSITION] = CARD_VALUE
Meaning that after i-th shuffle, card CARD_VALUE is in position POSITION. I don't want to give you all the specifics, but it will take another for loop, and the nested for-loop for printing needs to be independent of any other loop, occuring when everything else is done.
Looks like you have a few things concerning the for-loops that you need to look over carefully. Trace the program flow manually or with a debugger and you'll notice that some of those braces and code blocks need to be moved.
--TRY THIS--
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) { //initialize a to all zeroes
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
}
}
for(int i = 0; i < N; i++) //puts the deck in order, shuffles it, and records. N times
{
for (int j = 0; j < M; j++) //order the deck
deck[j] = j;
for(int j = 0; j < M; j++) { //shuffle the deck (same as yours except counter name)
int r = j + (int)(Math.random() * (M-j));
int t = deck[r];
deck[r] = deck[j];
deck[j] = t;
}
for(int j = 0; j < M; j++) //record status of this deck as described
{
int card_at_j = deck[j]; //value of card in position j
a[card_at_j][j]++; //tally that card_at_j occured in position j
}
} //big loop ended
for (int b = 0; b < M; b++) //print loop. a is MxM, so limit of N was wrong.
{
for (int c = 0; c < M; c++)
{
System.out.print(" " + a[b][c]);
System.out.println();
}
} //print loop ended
} //main() ended
} //class ended

Categories

Resources