我想在游戏中加入战斗, 我将如何制作它以便用户只有特定的时间来输入一个键 - 组合ex
String [] arr = {" A"," B"," C"," D"," E& #34;," F"}; 随机随机= new Random();
int fight = random.nextInt(arr.length);
if (arr[fight].equals("A")) {
System.out.println("You encountered an enemy!, Get ready to fight!");
try {
Thread.sleep(2000);
} catch (InterruptedException f) {
}
System.out.println("The enemy shoots a bullet!");
System.out.print("Enter \"10110\" to dodge!: "); ---------
pressp = i.next();-------- only 1 second to enter "10110"
try { else you get shot by bullet.
Thread.sleep(1000);
} catch (InterruptedException f) {
}
答案 0 :(得分:1)
您当前的代码将在扫描仪上的下一个方法调用中被阻止,因此您无法获得您正在寻找的内容。一旦你输入一些字符串,它只会睡一秒钟。您可能需要的是:
//define a callable which will be executed asynchronously in a thread.
static class MyString implements Callable<String> {
Scanner scanner;
public MyString(Scanner scanner) {
this.scanner = scanner;
}
@Override
public String call() throws Exception {
System.out.println("Enter now");
return scanner.next();
}
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
ExecutorService executor = Executors.newFixedThreadPool(1);//just one thread
MyString str = new MyString(userInput);
Future<String> future = executor.submit(str);//it will ask user for input asynchronously and will return immediately future object which will hold string that user enters.
try {
String string = future.get(1, TimeUnit.SECONDS);//get user input within a second else you will get time out exception.
System.out.println(string);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();//if user failed to enter within a second..
}
}