Я пытаюсь имитировать способ управления игровым вводом Кодингейм, который обычно выглядит так: < /p>
Код: Выделить всё
Scanner in = new Scanner(System.in);
int width = in.nextInt(); // columns in the game grid
int height = in.nextInt(); // rows in the game grid
// Game loop
while (true) {
int entityCount = in.nextInt();
// Process more input
}
выпуск
- Если я возвращаю -1 дважды последовательно во время вызовов чтения () , сканер < /code> рассматривает поток как закрытый , заставляя его бросить noshelementexception .
- для справки, я обнаружил, что возвращение фиктивного пространства символов () после -1 предотвратить помечение потока как закрытый. to nextint () , прежде чем читать больше данных из потока.
Код: Выделить всё
' '
Код: Выделить всё
private class GameStream extends InputStream {
private String buffer = "";
private int position = 0;
private int playerNum;
private boolean spaceFound = false;
public GameStream(int playerNum) {
this.playerNum = playerNum;
setBuffer(getTurnData(playerNum));
}
public GameStream setBuffer(String buffer) {
this.buffer = buffer;
position = 0;
return this;
}
@Override
public int read() throws IOException {
// Stop reading until the next call to nextInt()
if (spaceFound) {
spaceFound = false;
return -1;
}
if (position < buffer.length()) {
int c = buffer.charAt(position++);
if (c == ' ') {
spaceFound = true;
}
return c;
} else {
players.get(playerNum).getHisData = true;
// Prevent Scanner from closing the stream
setBuffer(" ");
return -1;
}
}
}
- Почему сканер call Read () дважды для одного Nextint () call?
- Какой правильный способ сделать сканер ждать новых данных при вызове nextint () не прибегая к фиктивным персонажам ()?
Код: Выделить всё
' '
Подробнее здесь: https://stackoverflow.com/questions/794 ... hat-has-mo
Мобильная версия