Category talk:Book:Java Programming
- Put new text under old text. Click here to start a new topic.
- Please sign and date your posts by typing four tildes (
~~~~
). - New to Wikibooks? Welcome! Ask questions, get answers.
public class GasPumpDisplay {
private int digits;
private int[] currentDigits;
private static final int MAX_DIGIT = 4;
public GasPumpDisplay(int numberOfPositions) {
this.digits = numberOfPositions;
this.currentDigits = new int[digits];
for (int i = 0; i < digits; i++) {
currentDigits[i] = 0;
}
}
public String nextElement() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < digits; i++) {
sb.append(currentDigits[i]);
}
// increment the current digits
for (int i = digits - 1; i >= 0; i--) {
if (currentDigits[i] < MAX_DIGIT) {
currentDigits[i]++;
break;
} else {
currentDigits[i] = 0;
}
}
return sb.toString();
}
public boolean hasMoreElements() {
for (int i = 0; i < digits; i++) {
if (currentDigits[i] < MAX_DIGIT) {
return true;
}
}
return false;
}
}
public class GasPumpTester {
public static void main(String[] args) {
GasPumpDisplay d = new GasPumpDisplay(3);
while (d.hasMoreElements()) {
System.out.println(d.nextElement());
}
}
}
``` 216.37.99.103 (discuss) 20:46, 5 December 2024 (UTC) Reply