Help with Two-Dimensional Arrays - java

First of all, Beginner here.
I'm using this code.
class MDArrays {
public static void main(String[] args) {
int[][] x;
int t=2;
x = new int[2][3];
for(int i=0; i<=1; i++) {
for(int j=0; i<=2; j++) {
x[i][j] = t;
t += 2;
System.out.println(x[i][j]);
}
}
}
}
It compiles perfectly, but when running it, after displaying 3 numbers correctly I'm getting the following error.
Exception in thread "main" java.Lang.ArrayindexOutOfBoundsException : 3 at MDArrays.main(MDArrays.java:13)
Where am I going wrong?

You are incrementing j while checking against i.
for(int j=0; i<=2; j++)
j will keep incrementing which will eventually give you an IndexOutOfBoundsException

for(int j=0; i<=2; j++) {
Is your problem. Try:
for(int j=0; j<=2; j++) {

I would write it like this:
class MDArrays
{
private static final int ROWS;
private static final int COLS;
private static final int START_VALUE;
private static final int INC_VALUE;
static
{
ROWS = 2;
COLS = 3;
START_VALUE = 2;
INC_VALUE = 2;
}
public static void main(String[] args)
{
final int[][] x;
int t;
x = new int[ROWS][COLS];
t = START_VALUE;
for(int row = 0; row < x.length; row++)
{
for(int col = 0; col < x[row].length; col++)
{
x[row][col] = t;
t += INC_VALUE;
System.out.println(x[row][col]);
}
}
}
}
The major difference is that I use the .length member rather than hard coded values. That way if I change it to x = new int[3][2]; then the code magically works and stays within its bounds.
The other big difference is that I use row/col instead of i/j. i/j are fine (and traditional) but I find when dealing with arrays of arrays (Java doesn't actually have multi-dimensional arrays) that it is easier to keep track of things if I use the more meaningful row/col (helps prevent you from doing things like for(int col = 0; row < x.length; col++)... which, incidentally, is the bug you have.

Related

Problem in extracting Even Columns from 2D Array

I'm trying to extract the entries of EVEN columns from the given 2D array.
The Code I have written is:
public static void main(String[] args) {
int [][] rearra = new int[5][3];
int[][] arra = { {01,02,03,04,05,06},
{11,12,13,14,15,16},
{21,22,23,24,25,26},
{31,32,33,34,35,36},
{41,42,43,44,45,46}};
rearra = method(arra);
for(int i=0; i<rearra.length; i++)
{
for(int j=0; j<rearra[0].length; j++)
System.out.println(rearra[i][j]);
}
}
static int[][] method(int [][] arr)
{
int temp = 3;
int [][] narra = new int[5][3];
//int nrow=0;
int ncol=0;
for (int row=0; row<5; row++){
for (int col=0; col<6; col++)
{
if ((arr[row][col]) % 2 == 0) {
narra[row][ncol] = (arr[row][col]);
ncol++;
}
}
}
return narra;
}
Now the output I want from this code should like this:
02 04 06
12 14 16
22 24 26
32 34 36
42 44 46
Can anyone guide me what's the problem in my program?
Move int ncol=0; inside outer loop:
for (int row=0; row<5; row++){
int ncol=0;
for (int col=0; col<6; col++)
{
Your idea is generally good, but you should also strive to write clean and understandable code. I will provide you with example that works for any array size and prints it nicely.
Your three main actions were all extracted into methods of their own, and thanks to that you can run it with any array.
Variable names have been replaced with meaningful ones so other people (and you sometimes in the future) can better understand what is going on.
Method for extracting even columns checks the length of each row, which needs not to be the same for all rows.
It works by checking if column index is even and if so, inserts into appropriate place in the new array.
I hope you will improve your skills by analyzing this example, good luck!
Full code:
public class ArrayExample {
public static void main(String[] args) {
int[][] arr = initializeArray();
int[][] evenColumnsOnly = getEvenColumns(arr);
printArray(evenColumnsOnly);
}
static int[][] initializeArray() {
int[][] arr = { {01,02,03,04,05,06},
{11,12,13,14,15,16},
{21,22,23,24,25,26},
{31,32,33,34,35,36},
{41,42,43,44,45,46}};
return arr;
}
static void printArray(int[][] arrayToPrint) {
for(int i = 0; i < arrayToPrint.length; i++) {
for(int j = 0; j < arrayToPrint[i].length; j++) {
System.out.print(String.format("%d\t", arrayToPrint[i][j]));
}
System.out.println();
}
}
static int[][] getEvenColumns(int [][] arr)
{
int [][] evenColumnsOnlyArray = new int[arr.length][];
for (int row = 0; row < arr.length; row++) {
int rowSize = arr[row].length / 2;
evenColumnsOnlyArray[row] = new int[rowSize];
for (int col = 0; col < arr[row].length; col++) {
if(col % 2 == 0 && col / 2 < rowSize) {
evenColumnsOnlyArray[row][col / 2] = arr[row][col];
}
}
}
return evenColumnsOnlyArray;
}
}

Need some tips with constructing a matrix from a given two- dimensional array JAVA

well I need to do the first constrctor and I was given in the method an array that i need to copy from.
the method is -
public Matrix(int[][] array)
what i tried is this :
public Matrix(int[][] array)
{
for(int i =0; i < array.length; i++ ) // running all over the rows
{
for ( int j=0; j < array[i].length; j++ ) // running all over the columns
{
_matrixArray[i][j]=array[i][j];
}
}
}
it says that im pointing to null? im trying to avoid alliasing so yeah, might need some help with this question please : )
You need to instantiate the array before adding elements to it. For example:
class Matrix {
private int[][] _matrixArray;
public Matrix(int[][] array)
{
this._matrixArray = new int[array.length][array[0].length];
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
this._matrixArray[i][j]=array[i][j];
}
}
}
}
You have to initialize matrix first. But note, the [][] means arrays of arrays, so in general case, different rows could have various coulmns amount.
public class Matrix {
private final int[][] matrix;
public Matrix(int[][] arr) {
matrix = new int[arr.length][];
for (int row = 0; row < arr.length; row++)
matrix[row] = Arrays.copyOf(arr[row], arr[row].length);
}
}

Tower of Hanoi using 2D arrays issue

I'm working on a Tower of Hanoi project for school which needs to ask the user how many disks there are and then it needs to create and then solve the tower with a visual included. How I decided to do it is by using 2D arrays and for the most part its working, my only problem is that I don't know how to move the disks while keeping it modular. Here is my code.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of disks");
int num = scan.nextInt();
int temp = num-(num-1);
int measure = num;
//initializing the towers
int[][] towers = new int[num][num];
for(int i = 0 ; i < num; i++)
{
for(int j=0; j <3; j++)
{
}
}
createRings(towers, num, temp);
moveDisk(towers,num);
}
// creating the rings
private static void createRings (int[][]towers, int num, int temp)
{
for(int i = 0; i<num; i++)
{
for(int j=0; j<3;j++)
{
towers[i][0] = temp;
}
temp = temp+1;
}
displayTower(towers, num);
}
// prints the array for display purposes
private static void displayTower (int[][] towers, int num)
{
for(int i = 0; i<num; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(towers[i][j]+"\t");
}
System.out.println();
}
}
//moves the numbers in the array that represents disks
private static void moveDisk(int[][]towers, int num)
{
System.out.println();
displayTower(towers, num);
}
Does anyone have any suggestions on what I could do?
I've changed your code a bit to make it more readable for me.
I changed the towers array. Now each tower is its own array inside the towers array (makes more sense IMHO).
Arrays in Java know their size. So you don't have to pass the length of the array as a parameter to every method.
I added a method getHighestIdx() which returns the index before the first 0 value in the array
I don't know, how the function moveDisk() was intended to work. I changed the declaration so that it makes sense to me. It now moves a disk from tower i to tower j
This should help you to implement the algorithm from the linked question.
Here is the changed code:
public static void main(String[] args) {
int numberOfRings = 6;
int[][] towers = new int[3][numberOfRings];
createRings(towers);
displayTowers(towers);
moveDisk(towers, 0, 2);
displayTowers(towers);
}
private static void createRings(int[][] towers) {
for (int j = 0; j < towers[0].length; j++) {
towers[0][j] = j + 1;
}
}
private static void displayTowers(int[][] towers) {
for (int i = 0; i < towers[0].length; i++) {
for (int j = 0; j < towers.length; j++) {
System.out.print(towers[j][i] + " ");
}
System.out.println("");
}
}
private static void moveDisk(int[][] towers, int fromIdx, int toIdx) {
int valToMove = towers[fromIdx][getHighestIdx(towers[fromIdx])];
towers[fromIdx][getHighestIdx(towers[fromIdx])] = 0;
towers[toIdx][getHighestIdx(towers[toIdx]) + 1] = valToMove;
}
private static int getHighestIdx(int[] tower) {
int i = 0;
while (i < tower.length && tower[i] != 0) {
i++;
}
return i - 1;
}

Concatenating 2-dimensional ragged arrays (Java)

I am trying to concatenate two two-dimensional arrays of different sizes. I have no idea why my method doesn't work. Java tells me, when I mouse over the "return xx": "Type mismatch: cannot convert from int[][] to int[]". When I mouse over "concatenateArr2d..." I get: "Illegal modifier for parameter concatenateArr2d: only final is permitted".
I don't understand why I am getting this error.
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int[][] xx = new int[t.length + s.length][];
for(i = 0; i < xx.length; i++)
{
xx[i] = new int[t[i].length + s[i].length];
}
return xx;
}
I still have to do the code to fill the entries but that should not be a problem.
Any help please? Thank you.
It looks to me that the code before the bit you pasted does not have aligned braces. You're probably inside a method when you try to declare this method.
public class HelloWorld{
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int jLength=0;
// The below line of code is to determine second dimension size of new array
jLength=Math.max(s[0].length, t[0].length);
int sIterate=0;
//new array created using size of first+second array for First dimension and maximum size for second dimension
int[][] xx = new int[t.length + s.length][jLength];
//first array copy
for(int i = 0; i < t.length; i++)
{
for(int j = 0; j < t[0].length; j++)
{
xx[i][j] =t[i][j];
}
}
//second array copy
for(int i = t.length; i < xx.length; i++)
{
for(int j = 0; j < s[0].length; j++)
{
xx[i][j] =s[sIterate][j];
}
sIterate++;
}
return xx;
}
public static void main(String []args){
int a[][]={{1,2},{2,3},{1,1}};
int b[][]={{1,2,3},{2,3,4}};
int c[][]=HelloWorld.concatenateArr2d(a,b);
//Output iteration
for(int i = 0; i < c.length; i++)
{
for(int j = 0; j < c[0].length; j++)
{
System.out.print(c[i][j]);
}
System.out.println();
}
}
}
note : The blanks filled by 'primitive type default value' like, for int its 0.
Output :
120
230
110
123
234

Turning 2 arrays into a two-dimensional array in java

Hi I am trying to take two arrays and turn them into one 2 dimensional array. However, I keep getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test5.sum(test5.java:12)
at test5.main(test5.java:38)
Here is my code:
public class test5 {
int[][] final23;
public int[][] sum(int[] x, int[] y) {
final23 = new int[2][x.length];
for (int i = 0; i < final23[i].length; i++) {
final23[1][i] = x[i];
final23[2][i] = y[i];
}
return final23;
}
public void print() {
for (int i = 0; i < final23[i].length; i++) {
for (int j = 0; j < final23[i].length; j++) {
System.out.print(final23[i][j] + " ");
}
}
}
public static void main(String[] args) {
int l[] = { 7, 7, 3 };
int k[] = { 4, 6, 2 };
test5 X = new test5();
X.sum(k, l);
X.print();
}
}
I am not really sure what the problem is. Sorry if the question is dumb, I am new to coding!
The problem is:
final23 [2][i] = y[i];
Java arrays always start at 0. So final23 only has [0] and [1].
Any array with n elements can go from 0 to n-1.
There is also a second problem with your program. You have this loop in both sum and print methods:
for (int i = 0; i < final23[i].length; i++)
In sum method it should be
for (int i = 0; i < final23[0].length; i++)
And in print method
for (int i = 0; i < final23.length; i++)
Otherwise you'll get ArrayIndexOutOfBoundsException again.
Note that the program works correctly only if both input arrays have the same length. This might be ok for your purposes, but keep that in mind.
Try
for (int i = 0; i < final23[i].length; i++)
{
final23 [0][i] = x[i];
final23 [1][i] = y[i];
}
Remember, all arrays are 0 based, even n-dimensional ones.

Categories