我正在尝试制作一个迷你矩阵的东西。它应该做的就是射出一个0或1.这个代码很好,但我试图让它在开始时进行倒计时(3,2,1 - 然后开始)。它通过activate()
在另一个文件中调用。
什么不起作用的是计时器。出于某种原因,它在前3个前面加上0:
03
2
1
它不会激活矩阵功能。这是代码,如果有人可以帮助我。
import java.util.Timer;
import java.util.TimerTask;
public class Matrix {
public boolean matrix = true;
static int interval;
static Timer timer;
public String activate() {
String done = "";
timer();
return done;
}
private void matrix() {
while(matrix) {
System.out.print((int) (Math.random()+0.5));
pressEnterToContinue();
}
}
private void timer() {
System.out.println("press ENTER to stop\n"+
"starting in");
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = 3;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
matrix();
}
private static final int setInterval() {
if (interval == 1) {
timer.cancel();
}
return interval--;
}
private void pressEnterToContinue() {
try
{
System.in.read();
matrix = false;
}
catch(Exception e) {}
}
}
只是一个FYI,pressToContinue()应该通过按ENTER结束while循环。
答案 0 :(得分:0)
它是由
打印出来的System.out.print((int) (Math.random()+0.5));
答案 1 :(得分:0)
使用ScheduledExecutorService
尝试此替代方案。
import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class Matrix {
public boolean matrix = true;
static int interval = 3;
static Timer timer;
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public String activate() {
String done = "";
scheduleTimer();
return done;
}
private void matrix() {
while(matrix) {
System.out.print((int) (Math.random()+0.5));
pressEnterToContinue();
}
}
public void scheduleTimer() {
System.out.println("Starting in:");
final Runnable timer = new Runnable() {
public void run() { System.out.println(setInterval()); }
};
scheduler.scheduleAtFixedRate(timer, 1, 1, TimeUnit.SECONDS);
try {
scheduler.awaitTermination(1, TimeUnit.DAYS);
matrix();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private final int setInterval() {
if (interval == 1) {
scheduler.shutdown();
}
return interval--;
}
private void pressEnterToContinue() {
try
{
System.in.read();
matrix = false;
}
catch(Exception e) {}
}
public static void main(String[] args){
Matrix mat = new Matrix();
mat.activate();
}
}