Code: Select all
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
}
Ausgabe
Wenn ich während der Read () Anrufe, der Scanner zweimal in Folge zurückgegeben habe, /Code> behandelt den Stream als geschlossen und führt dazu, dass er eine NoSuchelementException . (
Code: Select all
' '
Code: Select all
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;
}
}
}
Warum scanner call read () zweimal für einen einzelnen nächstenInt in () Anruf? ohne auf Dummy -Charaktere zurückzugreifen (
Code: Select all
' '
private String buffer = "";
private int position = 0;
public GameStream(String buffer) {
setBuffer(buffer);
}
public GameStream setBuffer(String buffer) {
this.buffer = buffer;
position = 0;
return this;
}
@Override
public int read() throws IOException {
if (position < buffer.length()) {
int c = buffer.charAt(position++);
return c;
} else {
System.out.println("player read all data");
//setBuffer("without_dummy_space_should_fail ");
return -1;
}
}
}
< /code>
Verwendung < /p>
GameStream gs = new GameStream("first turn finish_");
Scanner in = new Scanner(gs);
System.out.println(in.next() + " " + in.next() + " " + in.next());
gs.setBuffer("next turn_");
System.out.println(in.next()+ " " + in.next());
< /code>
out put < /p>
player read all data before
player read all data before
first turn finish_without_dummy_space_should_fail
player read all data before
player read all data before
next turn_without_dummy_space_should_fail
< /code>
Ich hoffe, ich habe mein Problem klar erklärt. Alle Erkenntnisse wären sehr geschätzt!