我目前正在做一个关于gridworld的塔防御项目(不确定这是否重要)。我有一个计时器,它从我的主类调用一个方法(TowerPlacer)来接收用户通过扫描器输入的文本。然而,在第一次通过之后,尽管TowerPlacer计时器正在运行,终端窗口仍然不允许我输入文本。
此外,无论出于什么原因,该方法似乎也会阻止所有bug的产生。尽管这座塔是从字面上什么也不做的。
下面是TowerPlacer的方法
public static void TowerPlacer ()
{
System.out.println ("You have " + money + " gold");
Scanner kbReader = new Scanner(System.in);
System.out.println ("Would you like to place a defense?");
System.out.println ("1. Yes");
System.out.println ("2. No");
answer = kbReader.nextInt();
kbReader.nextLine();
if (answer == 1) {
System.out.println ("Which defense would you like to place?");
System.out.println ("1. Study defense - 50 gold");
System.out.println ("2. Pencil defense - 100 gold");
System.out.println ("3. Pen defense - 150 gold");
System.out.println ("4. Cram defense - 200 gold");
Tanswer = kbReader.nextInt();
kbReader.nextLine();
System.out.println ("Defenses cannot be placed in the path of the critters.");
System.out.println ("Defenses not placed in viable locations will end the game.");
System.out.println ("What is the X-coordinate of the defense? (0 - 9)");
xCoord = kbReader.nextInt();
kbReader.nextLine();
System.out.println ("What is the Y-coordinate of the defense? (0 - 9)");
yCoord = kbReader.nextInt();
kbReader.nextLine();
if (Tanswer == 1) {
Study defense1 = new Study();
world.add(new Location(xCoord, yCoord), defense1);
System.out.println ("Defense Placed");
}
if (Tanswer == 2) {
Study defense2 = new Study();
world.add(new Location(xCoord, yCoord), defense2);
System.out.println ("Defense Placed");
}
if (Tanswer == 3) {
Study defense3 = new Study();
world.add(new Location(xCoord, yCoord), defense3);
System.out.println ("Defense Placed");
}
if (Tanswer == 4) {
Study defense4 = new Study();
world.add(new Location(xCoord, yCoord), defense4);
System.out.println ("Defense Placed");
}
}
if (answer == 2) {
System.out.println ("Construction cancelled");
}
if (answer != 1 && answer != 2) {
System.out.println ("Error, answer out of bounds");
}
System.gc();
}下面是我的计时器调用者的代码
public static void main(String[] args)
{
Timer timer = new Timer();
TimerA a = new TimerA();
timer.schedule(a,0,2000);
TimerC t = new TimerC();
timer.schedule(t,0,2000);
world.show();
System.out.println ("Please do not pause the game after starting.");
TowerPlacer();
}计时器本身
class TimerA extends TimerTask
{
public static int times = 0;
public void run()
{
times++;
if (times%10 == 0) {
BoxBugRunner.TowerPlacer();
}
if (times >= 1000000) {
//Stop Timer.
this.cancel();
}
}
}发布于 2013-06-08 14:46:35
错误出在您的TimerTask中。您需要的是:
class SayHello extends TimerTask {
public void run()
{
System.out.println("done");
}
}然后按如下方式更改main方法:
public static void main(String[] args)
{
int delay = 2000; // delay for 2 seconds
int period = 500; // repeat every .5 seconds
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SayHello(), delay, period);
}https://stackoverflow.com/questions/16996720
复制相似问题