7
7
import org .jetbrains .annotations .Nullable ;
8
8
9
9
import java .util .Iterator ;
10
+ import java .util .NoSuchElementException ;
10
11
11
12
/**
12
13
*
@@ -56,12 +57,18 @@ public MenuIterator(int startingRow, int startingCol,
56
57
currentPosition = shiftedPos ;
57
58
}
58
59
59
- //when it becomes empty
60
+ // when it becomes empty
60
61
return currentPosition ;
61
62
}
62
63
63
64
public @ Nullable Slot nextSlot () {
64
- return nextSlot (false );
65
+ Slot newPos = direction .shift (currentPosition , menu .getRows ());
66
+ if (newPos .getRow () >= menu .getRows () || newPos .getRow () < 1
67
+ || newPos .getColumn () > 9 || newPos .getColumn () < 1 ) {
68
+ return null ;
69
+ }
70
+ currentPosition = newPos ;
71
+ return newPos ;
65
72
}
66
73
67
74
@ Override
@@ -72,12 +79,13 @@ public boolean hasNext() {
72
79
73
80
@ Override
74
81
public MenuItem next () {
75
- return menu .getItem (nextSlot ());
82
+ Slot slot = nextSlot (false );
83
+ if (slot == null )
84
+ throw new NoSuchElementException ("Used MenuIterator#next() but no more items to iterate over" );
85
+ return menu .getItem (slot );
76
86
}
77
87
78
88
public enum IterationDirection {
79
-
80
-
81
89
HORIZONTAL () {
82
90
@ Override
83
91
Slot shift (Slot oldPos , int maxRows ) {
@@ -117,7 +125,7 @@ Slot shift(Slot oldPos, int maxRows) {
117
125
118
126
@ Override
119
127
Slot shift (Slot oldPos , int maxRows ) {
120
- int row = oldPos .getRow () + 1 ;
128
+ int row = oldPos .getRow () - 1 ;
121
129
if (row < 1 ) {
122
130
row = oldPos .getRow ();
123
131
}
@@ -130,7 +138,7 @@ Slot shift(Slot oldPos, int maxRows) {
130
138
Slot shift (Slot oldPos , int maxRows ) {
131
139
int row = oldPos .getRow () + 1 ;
132
140
if (row > maxRows ) {
133
- row = 6 ;
141
+ row = oldPos . getRow () ;
134
142
}
135
143
return new Slot (row , oldPos .getColumn ());
136
144
}
@@ -140,21 +148,21 @@ Slot shift(Slot oldPos, int maxRows) {
140
148
RIGHT_ONLY {
141
149
@ Override
142
150
Slot shift (Slot oldPos , int maxRows ) {
143
- int col = oldPos .getColumn () + 1 ;
151
+ int col = oldPos .getColumn ()+ 1 ;
144
152
if (col > 9 ) {
145
- col = 9 ;
153
+ col = oldPos . getColumn () ;
146
154
}
147
155
return new Slot (oldPos .getRow (), col );
148
156
}
149
157
},
150
158
151
159
152
- LEFT_ONLY {
160
+ LEFT_ONLY {
153
161
@ Override
154
162
Slot shift (Slot oldPos , int maxRows ) {
155
- int col = oldPos .getColumn () - 1 ;
163
+ int col = oldPos .getColumn ()- 1 ;
156
164
if (col < 1 ) {
157
- col = 1 ;
165
+ col = oldPos . getColumn () ;
158
166
}
159
167
return new Slot (oldPos .getRow (), col );
160
168
}
0 commit comments