I am new to Java and I need to write a method next()that will return the current value from a 2D array.
For example, we can have:
int[][] values = {{1, 2}, {3, 4}, {5, 6}};
When we use it next()for the first time, it returns 1, the second - 2, the third - 3etc.
My solution is to make a 1D array from this 2D array:
public int[] convert(int[][] array) {
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
count++;
}
}
int[] result = new int[count];
int index = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
result[index] = array[i][j];
index++;
}
}
return result;
}
And then just get the value from this new 1D array ( position- this is a class field = 0, valuesalso a class field - int[][] values):
public int next() {
int[] tmp = convert(values);
int result = tmp[position];
position++;
return result;
}
But it is obvious that this solution is not the best. Is there any way to do this without talking to arrays?
Something similar to Iterator next()and hasNext()?
. , , :
public class ArrayConverter {
private final int[][] values;
private int upper = 0;
private int lower = -1;
public ArrayConverter(int[][] values) {
this.values = values;
}
public int next() {
lower++;
int result = 0;
try {
result = values[upper][lower];
} catch (ArrayIndexOutOfBoundsException a) {
lower = 0;
upper++;
try {
result = values[upper][lower];
} catch (ArrayIndexOutOfBoundsException r) {
upper = 0;
lower = -1;
System.out.print("Reached the end of data. Indexes will be zeroed.");
}
}
return result;
}
}
- try/catch, . ?