我试图在2分钟内读取字符串,但最后ListOfwords只获得第一个字。有什么建议吗?
ArrayList<String> listOfWords = new ArrayList<String>();
String word;
try{
System.out.println("Guess words: ");
Thread.sleep(time*1000*120);
word = in.next();
listOfWords.add(word);
System.out.println("Out of time!!!!!!\n");
} catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(listOfWords);
答案 0 :(得分:0)
使用Timer
来安排任务(即读取字符串),尝试使用以下代码:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
ArrayList<String> listOfWords = new ArrayList<String>();
String word;
System.out.println("Guess words: ");
try {
Thread.sleep(60000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Scanner in = new Scanner(System.in);
word = in.next();
listOfWords.add(word);
System.out.println(word);
System.out.println("Out of time!!!!!!\n");
}
}, 0, time);