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

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

Related

Filling 2D Array in Java and getting ExceptionOutOfBounds

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

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

indexoutofbound error when shifting 2D array elements java

public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length + amount; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount < original.length) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
Hi,
I am trying to write a method that will shift the elements in my 2-D array to the left by some arbitrary amount. I don't want to loop the values back around, but instead fill the empty arrays with some fill_value which is already predefined. And if the shift amount is more than the orignial length, I would just return an image with only fill_value. However, this function is throwing an arrayindexoutofbound Error. But I can't think of how I should change my for loop to fix the error. Any help is appreciated! Thank you!
I believe it's because in your second outer for loop, the condition is cols < length + amount, so it will continue past the edge of the array if amount > 0. You could step through your code with a debugger and see exactly where it's going out of bounds.
The error is occurring because of following line:
shifted[cols][rows] = original[cols - amount][rows];
When cols=0, rows=0, amount=2 (say), it is trying to access original[-2][0] which does not exist.
Instead you may use following:
public class overflow1 {
static int a[][] = {{1,2,3,4,5,6},{2,3,4,5,6,7},{3,4,5,6,7,8}, {4,5,6,7,8,9}, {5,6,7,8,9,10}, {6,7,8,9,10,11}};
static int b[][] ;
static int FILL_VALUE =0;
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length ; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount >=0) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
public static void main(String[] arggs) {
b=shift(a,2);
System.out.println("Original array:");
for(int i=0; i<a.length; i++){
for (int j=0; j<a[i].length; j++){
System.out.print(a[i][j]+ ":");
}
System.out.println();
}
System.out.println("After shift by 2 array:");
for(int i=0; i<b.length; i++){
for (int j=0; j<b[i].length; j++){
System.out.print(b[i][j]+ ":");
}
System.out.println();
}
}
}
Here is the output for the sample:
Original array:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
5:6:7:8:9:10:
6:7:8:9:10:11:
After shift by 2, array:
0:0:0:0:0:0:
0:0:0:0:0:0:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:

How to create two dimensional grid with two-d. array?

This is my current code:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
/*for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + "");
}
}*/
}
}
I can't seem to do it. I got confused and I removed the part of testing w/commenting. Just ignore that.
I am aiming to get a two dimensional array like this:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
However, I just don't get it. How can I get that result? I'm a beginner at java.
First, you need to populate the array with data, and you forgot System.out.println for each row of the array.
int [][] twoD = new int [5][5];
// populate array with data
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = (j+1)*(i+1);
}
}
// print result
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j]);
System.out.print(" ");
}
System.out.println();
}
You have to populate the data as well:
int[][] arr = new int [5][5];
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
arr[i][j] = (j+1)*(i+1);
}
}
And the code to print would be:
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
You are doing fine, you just need to put line jump System.out.println(); every time the second for ends
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You are on the right track, that for loop will print out the array like that, all you need to do is print a new line character after finishing the for(j) loop. But, at least in the snippet you posted, you aren't actually doing any assignments, so there aren't any values in your array to print, Java will initialize all ints to zero for you.
The array doesn't just automatically populate with incrementing integers, rather each cell of the array will automatically initialized to 0, you have to set the values you want the array to contain. You can use the concept of your testing class to do this if you wish, just set each cell of the 2D array to a certain value. After that, you can print out the array, making sure to print a each row of the array on a new line. For instance:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
int increment = 1;
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = increment++;
}
}
for(i = 0; i<5; i++){
for(j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
The first set of nested for loops will set each of the cells of the 2D array to the incremented integers you want (note increment++ will first set the cell to the value increment currently is, then add one to the variable). The second set of nested for loops will print out the array as you desire.
refer this code
int[][] twoD = new int[5][5];
// add values to array
for (int i = 0; i < 5; i++) {
int val = 1;
val = val + i;
for (int j = 0; j < 5; j++) {
twoD[i][j] = val * (j + 1);;
}
}
// Print array
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
as others pointed out you need to print it nicely to see the pattern, i and j are indices of your array. However, I see that you have a nice pattern so just running two loops won't solve the problem.
Maybe something like this would help (not giving exact answer intentionally)
int [][] twoD = new int [5][5];
int i;
// initialize
int c = 1; int j = 0;
for(c=1; c<5; c++) {
for( i = 1; i<=5; i++){
twoD[i-1][c-1] = c*c*i; twoD[c-1][i-1]=c*c*i;
}
}
for( i = 0; i<5; i++) {
for( j = 0; j<5; j++) {
System.out.print(twoD[i][j]);System.out.print(" " );
}
System.out.println("\n");
}

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

Categories