Reputation:
iam new to programming.iam wrking on a quiz game software. here i want a count down to be printed as "3,2,1,go...go...go"
package t2;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = 3;
System.out.println("3");
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval() {
String go="go...go...go";
if (interval == 2)
{
timer.cancel();
return go;
}
return --interval;
}
}
this says that setInterval() has int as return value.if i place System.out.print("go");
in the place of return go;
it prints go and prints 1 which is out of requirement. please any buddy can tell me how to do this.
Upvotes: 0
Views: 3170
Reputation: 62841
One option would be to change your setInterval() method to return a string like such:
private static final String setInterval() {
String go="go...go...go";
if (interval == 2)
{
timer.cancel();
return go;
}
--interval;
return String.valueOf(interval);
}
Upvotes: 1
Reputation: 94429
Change the return type of setInterval
to object to take advantage of the overloaded println
method and the conditional should check for 1 instead of 2. Also use print
instead of println
to have the output on the same line.
private static final Object setInterval() {
String go="go...go...go";
if (interval == 1)
{
timer.cancel();
return go;
}
return --interval;
}
Full Example
package t2;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = 3;
System.out.print("3,");
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.print(setInterval() + ",");
}
}, delay, period);
}
private static final Object setInterval() {
String go = "go...go...go";
if (interval == 1) {
timer.cancel();
return go;
}
return --interval;
}
}
Upvotes: 0