1

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?

3
  • 3
    You should never catch an ArrayIndexOutOfBoundsException, just check whether the index is within bounds beforehand. Commented Feb 1, 2017 at 8:14
  • codereview.stackexchange.org is a better place to submit code fragments for improvement / suggestions Commented Feb 1, 2017 at 11:00
  • 1
    @tucuxi I'm pretty sure you mean codereview.stackexchange.**com** ... Commented Feb 1, 2017 at 11:03

1 Answer 1

1

Use array.length for range checks

Try this:

private int upper = 0;
private int lower = 0;

public int next() {
    if(lower >= values[upper].length){
        upper++;
        lower = 0;
    }
    if(upper >= values.length){
        throw new NoSuchElementException("Reached end");
    }
    int result = values[upper][lower++];
    return result;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.