Filling 2D Array in Java and getting ExceptionOutOfBounds - java

I searched some entries, but could not answer my question correctly myself.
I'm trying to fill a 2-dimensional array with values.
As a test I'm currently doing this by trying to fill the array with the int number 1.
I do not understand my mistake.
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}

Use index 0 to length-1 (as array index start with 0)
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
}

just debug it and you can see, that
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
i, and j change values from 0 to 6, it means that it get's out of arrays bounds ( you iterate over 7 lements, instead of 6 ), just remove = sign in loop bodies
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}

Your board array is of size 6x6 hence the board.length is 6.
When you run the loop for (int j = 0; j<=board.length; ij+) it will run from 0 up to 6 but the array indexing is from 0 to 5. So when j=6, ExceptionOutOfBounds occurs since it will be referring to index board[0][6].
Change the condition in both the loops from <=board.length to <board.length

Related

How to Create 2D Array with #1 in Random Positions for Specific Number of Times

I want to create an 8x8 array with JAVA, in which i want to have 1 eight times in random generated positions. All the other positions of the array are going to be 0. I am using this code but obviously it is not filling the array with 1 for a specific number of times.
public static void main(String[] args) {
int [][] arr = new int [8][8];
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
arr[i][j] = (int) (Math.random()*2);
}
}
for(int k = 0; k < 8; k++){
for(int l = 0; l < 8; l++){
System.out.print(arr[k][l] + " ");
}
System.out.println();
}
}
}
import java.util.Random;
int[][] array = new int[8][8];
Random r = new Random();
int a = r.nextInt(8);
int b = r.nextInt(8);
//insert 8 random 1's in the 8x8 matrix, no duplicates
//by default in Java the other places are
for(int i = 0; i < 8; i++){
while(array[a][b] == 1){
a = r.nextInt(8);
b = r.nextInt(8);
}
array[a][b] = 1;
}

ArrayIndexOutOfBound Exception when reversing array order with multidimensional arrays:

So I'm currently playing around with multidimensional arrays (2D) and I'm trying to reverse the order of each array in a 2-d array.
So I have a 2D-array set as:
int firstArray[][] = {{5,6,7,8,9,10}, {11,12,13,14,15,16}}
I have manually looked through the issue to see where I may have went wrong, to see which part of my code would end up going out of bounds in regards to my for-loops. The -1 part also caught me off guard.
I have began doing reverses on a regular 1-d array, and tried to apply the same concept to multidimensional arrays.
class Test2 {
public static void main (String[] args) {
int firstArray[][] = {{5,6,7,8,9,10}, {10,11, 12, 13, 14, 15}};
System.out.println("FIRST ARRAY");
display(firstArray);
}
public void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num.length-1-j];
num[i][num.length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
}
I want the output using my display method to basically be a reverse of the arrays in my 2-d array:
10 9 8 7 6 5
15 14 13 12 11 10
The issue that I'm getting is an
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1
ArrayIndexOutOfBoundsException: -1
at Test2.display(Test2.java:30)
at Test2.main(Test2.java:20)
You are using the length of the wrong dimension.
With num.length you are using the number of rows and not the number of columns of the current row.
You need to change that to num[i].length.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
Notice you wrote num[i][num.length-1-j];
num.length-1-j is basically 2 - 1 -j.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2 ; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}

Create a 2d array from an ArrayList<Integer>

I have an ArrayList and I want to create a method that will turn it into a 2d array, int[][].
This new 2d array will represent a matrix and it has to be square, so for example if I use [8, 2, 3, 0] the ressult will be {8,2}
{3,0}
public static int[][] convertIntegers(ArrayList<Integer> integers){
int m = (int) Math.sqrt(integers.size());
int[][] ret = new int[m][m];
int cont = 0;
for(int i=0; i<m+1 ; i++)
{
for(int j=0; j<m; j++)
{
cont = cont + 1;
ret[i][j] = integers.get(cont);
;
}
}
return ret;}
Your implementation is almost ok, except for some off-by-one errors:
You need to increment cont after the integers.get call, not before. If you increment before, then the first element of the list will be skipped. An easy way to fix that is to move the incrementing inside the inner loop, counting it together with j.
The outer loop should go until i < m instead of i < m + 1
With the errors fixed:
for (int i = 0, cont = 0; i < m; i++) {
for (int j = 0; j < m; j++, cont++) {
ret[i][j] = integers.get(cont);
}
}
Btw, another way is without using cont at all,
calculating the correct position using i, j and m:
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = integers.get(i * m + j);
}
}

How to flatten a 2-dimensional array into a 1-dimensional array

How would i transfer a 2d array into a 1d array in java. I have the code for the 2d array but dont know where to start.
The output of the 2d array is a 8 by 10 grid with the numbers going from 1-80.
public class move
{
public static void main (String[] args)
{
int[][] twoarray = new int[8][10];
int i ;
int j ;
for(i =0; i < 8; i++)
{
for(j = 0; j < 10; j++)
twoarray[i][j] = (i * 10 + j+1);
}
for(i = 0; i < 8; i++)
{
for(j = 0; j < 10; j++)
{
System.out.print(twoarray[i][j]);
System.out.print(" ");
}
System.out.println();
}
int[] array = new int[80];
}
}
Using Java 8
int[] array = Stream.of(twoarray)
.flatMapToInt(IntStream::of)
.toArray();
Using Java 7 or older
int[] array = new int[80];
int index = 0;
for (int[] row : twoarray) {
for (int val : row)
array[index++] = val;
}
You can do in your for loop:
int[] array = new int[80];
int k=0;
for(i = 0; i < 8; i++){
for(j = 0; j < 10; j++){
array[k++]=twoarray[i][j];
}
}

Why the following piece of java code throws run time error?

int[][] input = new int[3][];
int count = 1;
for(int i = 0; i <= 2 ; i++ ) {
for(int j = 0; j <= 2; j++) {
input[i][j] = count++;
}
}
Fifth line throws an error.
Second dimension of the array is empty.
int[][] input = new int[3][];
Try this:
int[][] input = new int[3][3];
int[][] input = new int[3][];
this type of array are called ragged array.
in you have to define the size of column for each row. like this:
input[0]=new int[2];//for row 1 (row 1 contain 2 column)
input[1]=new int[5];//for row 2 (row 2 contain 5 column)
input[2]=new int[1];// for row 3 (row 3 contain 1 column)
so define column size for each row as you wish
/*Ragged Arrays
are multidimensional arrays in which
the rows have different no of cols.
*/
class Ragged
{
public static void main(String args[])
{
//declaration of a ragged array
int arr[][] = new int[3][];
//declaration of cols per row
arr[0] = new int[4];
arr[1] = new int[2];
arr[2] = new int[3];
int i, j;
for(i =0; i< arr.length; i++)
{
for(j =0 ; j< arr[i].length; j++)
{
arr[i][j] = i + j+ 10;
}
}
for(i =0; i< arr.length; i++)
{
System.out.println();//skip a line
for(j =0 ; j< arr[i].length; j++)
{
System.out.print(arr[i][j] + " ");
}
}
//-------------more----------------
int temp[];//int array reference
//swap row2 and row3 of arr
temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;
System.out.println();//skip a line
for(i =0; i< arr.length; i++)
{
System.out.println();//skip a line
for(j =0 ; j< arr[i].length; j++)
{
System.out.print(arr[i][j] + " ");
}
}
}//main
}//class
/*
TO declare a ragged array define a
multi dimensional array with the val
of last dimension missing.
The explicitly define the size of
the last dimension for all the rows.
*/
You need to initialize the second dimension
1) int[][] input = new int[3][3];
or
2)
for(int i = 0; i <= 2 ; i++ ){
input[i] = new int[3];
}
Because you second array dimension is not specified.
This should run:
int[][] input = new int[3][3];
int count = 1;
for(int i = 0; i <= 2 ; i++ ){
for(int j = 0; j <= 2; j++){
input[i][j] = count++;
}
}
See executable example
Because you didn't specify the second dimension size.
You need specify size for second array during initialization.
Also you can use .length property of array to avoid hard coded sizes.
int[][] input = new int[3][3];
int count = 1;
for(int i = 0; i <= input.length ; i++) {
for(int j = 0; j <= input[i].length; j++) {
input[i][j] = count++;
}
}

Categories