There is a program that opens a file, reads text from it and splits it into pages. These pages can be scrolled back and forth with the Enter and Backspace keys. Sooner or later, there will be an exceptional situation when we want to look at the next one (go beyond the limits) on the last page of the book, or we want to go back one page to the 1st page Scrolling methods:
public void nextP() { // if (pageNumber == page.size() - 1) { // } else pageNumber++; for (int i = 0; i < page.get(pageNumber).size(); i++) System.out.println(page.get(pageNumber).get(i)); } public void backP() { // if (pageNumber == 0) { // pageNumber++; // } else { pageNumber--; for (int i = 0; i < page.get(pageNumber).size(); i++) System.out.println(page.get(pageNumber).get(i)); }
Here I have documented a “check”, why do we need this if we can catch the error (am I thinking correctly?). The block listener calling the above methods:
try { addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == e.VK_ENTER) { nextP(); } if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { backP(); } } }); } catch (IndexOutOfBoundsException e) { System.out.println("Выход за пределы книги") }
And all the same takes off IndexOutOfBoundsException. How to correctly make it so that this error does not crash?
Ideally, to achieve such a result, while on the last page we pressed Enter (go to the next (non-existent) page), but the program did not react at all (did not display the last page again) and continued to show that very last page.