如何解决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
解决方法
TimerTask.run
方法中的“ return”从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++) {
...
}
但是,这只会检查问题之间的超时。在程序等待用户键入时,不能中断它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。