2014-01-26 74 views
1

因此,在我的聊天机器人程序中,我想让它在等待大约2秒后等待它回答之前说了些什么。我尝试了睡眠方法,但这使得我所说的延迟以及... 我试图找到等待方法上的东西,但我似乎无法找出它是如何工作的,所以这里是我的一段代码来回答。 我想在等待2秒后再做“addText(ft.format(dNow)+”| - >你:\ t“+ quote);”部分,然后编写聊天机器人Chatbot在说点什么和获得答案之间的延迟

if(e.getKeyCode()==KeyEvent.VK_ENTER) 
     { 
         Date dNow = new Date(); 
         SimpleDateFormat ft = 
         new SimpleDateFormat ("hh:mm:ss"); 

      input.setEditable(false); 
      //-----grab quote----------- 
      String quote=input.getText(); 
      input.setText(""); 
      addText(ft.format(dNow) + " |-->You:\t"+quote); 

      quote.trim(); 
      while(
       quote.charAt(quote.length()-1)=='!' || 
       quote.charAt(quote.length()-1)=='.' || 
       quote.charAt(quote.length()-1)=='?' 
      ) 
      { 
       quote=quote.substring(0,quote.length()-1); 
      } 
      quote=quote.trim(); 
      byte response=0; 

      //-----check for matches---- 
      int j=0;//which group we're checking 
      while(response==0){ 
       if(inArray(quote.toLowerCase(),chatBot[j*2])) 
       { 
        response=2; 
        int r=(int)Math.floor(Math.random()*chatBot[(j*2)+1].length); 
        addText("\n" + ft.format(dNow) + " |-->Miku\t"+chatBot[(j*2)+1][r]); 
        if(j*2==0){ 
        try (BufferedReader br = new BufferedReader(new FileReader("mikuname.txt"))) { 
         String name; 
         while ((name = br.readLine()) != null) { 
         addText(name +"!"); 
         } 
        } catch (IOException e1) { 
         // Do something with the IO problem that occurred while reading the file 
        } 
       } 
       } 
       j++; 
       if(j*2==chatBot.length-1 && response==0) 
       { 
        response=1; 
       } 
      } 

回答

1

Thread.sleep(),如果你有不同的线程处理的反应只会工作的答案。因为你没有,你需要采取不同的方法。

使用ScheduledExecutorService对象将任务安排在未来两秒钟。从here采取

// Create the service object. 
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5); 
// Schedule the task for the next 5 seconds. 
ScheduledFuture scheduledFuture = 
scheduledExecutorService.schedule(new Callable() { 
    public Object call() throws Exception { 
     System.out.println("Executed!"); 
     return "Called!"; 
    } 
}, 
5, 
TimeUnit.SECONDS); 

代码。

相关问题