I'm a beginner in Java, and I need to write a next() method, which will return current value from 2D array and move pointer to the next element. It's similar to Iterators's next() method.
For example, we may have:
int[][] values = {{1, 2}, {3, 4}};
When we are using next() at the first time, it returns 1 (pointer moved to next index, now pointer stands at 2), second use - 2(+move of pointer), third - 3(+move pointer), etc.
I wrote some bad code to illustrate what I want to do:
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;
}
}
Are there any ways to do it better, especially without using try/catch blocks?
codereview.stackexchange.**com** ...