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
}
,如何管理游戏模拟的自定义输入?
我正在尝试模拟Codingame管理游戏输入的方式,通常看起来像这样:
InputStream
Scanner
read()
似乎对单个调用nextInt()
的方法进行了双调用
。issue
如果我在电话期间连续返回两次,则
-1
将流视为clated,导致它扔了一个
read()
Scanner
后返回一个虚拟空间字符(
NoSuchElementException
)
' '
防止流被标记为封闭。地,我希望
-1
在阅读流中的更多数据之前,要等待下一个呼叫。
Scanner
问题thy thow t两次打电话给单个电话?
在不诉诸虚拟字符(
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;
}
}
}
usage
Scanner
read()
在这里是如何抛出的。
第一次呼吁
nextInt()
Scanner
然后返回第一个单词“第一个”。第二个呼吁
nextInt()
从扫描仪自己的缓冲区中读取,并成功地读取了第二个单词“ turn”。
第三次呼叫
' '
读为“完成_”,但流到此结束。这不是一个完整的令牌(扫描仪的
class GameStream extends InputStream {
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;
}
}
}
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());
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
更改它。另一方面,如果NoSuchElementException
Does将其视为默认情况下的代币分配器。
如果您不喜欢从
next()
返回空间(我认为这是一个合理的解决方案),则可以在设置缓冲区时在末端添加一个空间。
-1
如果您正在阅读
Text
,您应该实现一个
next()
。例如:next()
使用站点保持不变,但请记住在最后添加一个定界符。
对方考虑使用next()
/delimiter()
-1