首页 > 解决方案 > Java 程序不会终止

问题描述

我的程序在计时器启动后继续运行...我希望在计时器启动后不再进行输入并转到 showResult() 函数...但是程序在显示结果后跳回接受输入。

如果计时器没有启动,该程序非常好......但是当计时器打开时......我认为一个线程仍然停留在我接受输入的函数上,当标记时程序回到那里已显示。我不希望发生这样的行为。一旦计时器启动,程序应该停止接收输入,并且永远不会再回到它。我不知道该怎么做。我是这个领域的新手:P

import java.util.*;

class Quiz {
  private String questions[][];
  private int marks;
  
  public Quiz(){
    marks = 0;
    questions = new String[][]{{ 
      "Name of the screen that recognizes touch input is :",
      "Recog screen",
      "Point Screen",
      "Android Screen",
      "Touch Screen",
      "4",
      "" 
    }};
    //questions as stated above is filled.
  }


  public void displayQues(int x){
      System.out.print("\n Q. "+questions[x][0]);
      System.out.print("\n 1. "+questions[x][1]);
      System.out.print("\n 2. "+questions[x][2]);
      System.out.print("\n 3. "+questions[x][3]);
      System.out.print("\n 4. "+questions[x][4]);
  }
 
  public void getResponse(){
    Timer t = new Timer();
    t.schedule(
      new TimerTask(){
        public void run(){
          System.out.print("\n Time is up!");
          t.cancel();
          return;
        }
      }, 5*1000L);
    
    System.out.print("\n Timer of 5 Minutes started!");
    String temp = "";
    for(int i = 0;i < 10;i++){
      int x = genDiffRndNum(temp);
      displayQues(x);
      System.out.print("\n Enter your answer: ");
      if(validateAnswer(x))
        questions[x][6] = "T";
      else
        questions[x][6] = "F";
      temp = temp+x;
    }
  }

  public int genDiffRndNum(String str){
    while(true){
      int n = (int)(Math.random()*10);
      if(str.indexOf(Integer.toString(n))==-1)
        return n;
    }
  }

  public boolean validateAnswer(int ques){
    Scanner sc = new Scanner(System.in);
    int ans = sc.nextInt();
    sc.close();
    if(Integer.parseInt(questions[ques][5])==ans){
      marks += 3;
      return true;
    }
    marks -= 1;
    return false;
  }

  public void showResults(){
    System.out.print("\n Marks Obtained: "+marks);
    System.exit(0);
  }

  public static void main(String[] args) {
    Quiz q = new Quiz();
    q.getResponse();
    q.showResults();
    System.exit(0);
  }
}

任何建议将不胜感激:D

标签: javatimerterminate

解决方案


方法内的“return”从TimerTask.run方法中返回TimerTask.run。它不会使getResponse()方法退出。

要退出getResponse(), TimerTask 必须设置某种标志,由 读取getResponse()。一种可能性是使用AtomicBoolean对象。它最初设置为false,当计时器触发时,它更改为true

    AtomicBoolean timeIsUp = new AtomicBoolean(false);
    Timer t = new Timer();
    t.schedule(new TimerTask() {
        public void run() {
            System.out.print("\n Time is up!");
            timeIsUp.set(true);
            t.cancel();
        }
    }, 5 * 1000L);

循环中getResponse需要检查时间是否到了:

    for (int i = 0; i < 10 && !timeIsUp.get(); i++) {
        ...
    }

但是,这只会检查问题之间的超时。当程序在等待用户输入时,它不能被中断。


推荐阅读