java程序不终止

64jmpszr  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(345)

我的程序在计时器启动后继续运行。。。我不想在计时器启动并转到showresult()函数后再进行任何输入。。。但程序在显示结果后会跳回获取输入。
如果定时器不启动,程序就完全正常了。。。但当计时器打开时。。。我认为线程仍然停留在函数中,在那里我采取的输入和flw程序返回那里时,标记已显示。我不想这样的行为发生。一旦计时器启动,程序就应该停止接收输入,并且永远不要再返回到它。我不知道怎么做。我是这个领域的新手: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);
  }
}

如有任何建议,我们将不胜感激

hjqgdpho

hjqgdpho1#

“返回”在 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++) {
        ...
    }

但是,这将只检查问题之间的超时。当程序等待用户键入时,不能中断。

相关问题