My while (true) loop method only seems to run once!
Hi guys,
I've recently written a block of code to serve as an internal integer-based clock for another program I'm using.
Code :
public class WorldTime
{
public String gametime;
final int sunrise = 600;
final int sunset = 1800;
public int timevalue = 0;
public Boolean isnight;
public Boolean isday;
public Boolean issunrise;
public Boolean issunset;
public Boolean runclock;
public int currentTime()
{
while (true)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException timevalue)
{
}
if (timevalue == 2400)
{
resetTime();
}
else
{
timevalue++;
}
return timevalue;
}
}
There are a lot more other methods in the class, but this is the only one I'm interested in for this question.
Now, to test that this counting system is working, I created a dummy program to merely test to method value to see if this method was working.
Code :
public class TimeTest
{
public static int cool;
public static void main(String args[])
{
WorldTime base = new WorldTime();
cool = base.currentTime();
testRun();
}
public static void testRun()
{
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = new WorldTime().currentTime();
if (x > 0)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException timevalue)
{
}
System.out.println("The program's time is: " + cool);
}
}
}
The code compiles easily.
I have it sleep for 5 seconds to see if the counting method works. However, the output is always "1", regardless of how long the sleep value is, or how long I wait to input an x value.
What's going on here? I'm not exactly a java expert, but I have enough experience writing code that I thought this should work.
Thanks in advance!
Re: My while (true) loop method only seems to run once!
Quote:
Originally Posted by
ajfonty
Code :
while (true)
{
...
return timevalue;
}
}
What do you think the return does? Follow the code you have through - it looks pretty straightforward that it will only execute once.
Re: My while (true) loop method only seems to run once!
You return a value in your loop. Whenever you return something, all of the execution afterwards is ignored.