如何从System.in?

时间:2016-01-28 03:00:54

标签: java console

我正在使用Java套接字实现基于控制台的Tic Tac Toe游戏。我的实施目前运作良好 - 也就是说,如果双方都正常游戏并等待轮到他们。我现在遇到的问题是,如果其中一个玩家在其他玩家的回合中输入任何内容,因为我使用Scanner#nextLine()获取他们的输入,当它成为他们自己转过来,它会立即切换回另一个人,当他们没有轮到服务器时发送他们发送的第一件东西(如果这是有道理的)。这显然是非常不受欢迎的。我需要的是用户提交的所有输入都被丢弃,当轮到他们时,程序应该等待新输入并使用它。

为了证明我所指的行为,这里有一个简短的代码示例(为了简单起见,不是直接来自我的Tic Tac Toe,但是类似的概念):

Scanner r = new Scanner(System.in);

// Simulate other player's turn by sleeping for 5secs:
Thread.sleep(5000);
// Imagine player inputs things here, when they aren't supposed to...

System.out.println("Input: ");
// What I want is for the code to pause here and wait for input
//     no matter what, but instead, if you inputted something
//     while the thread was sleeping, it will print here.
System.out.println(r.nextLine());

谢谢!

0 个答案:

没有答案
相关问题