-2
   import java.util.Scanner;
   import java.lang.Thread;

   class OrigClass {
   public static void main (String[] args){


   for(int i = 0; i<=10;i++){
      System.out.println(i);
      thread.sleep(1000);
   }
  }
 }

As you can see, I want the program to count up to 10. What do I need to type to get it to work?

I probably should have said the error is "thread cannot be resolved" in Eclipse.

Sam
  • 97
  • 2
  • 4
  • 11
  • 1
    Your code seems alright to me. It should print one number every second. – Geeky Guy Jun 26 '13 at 12:19
  • What do you mean by "what do I need to type"? Like, how to compile/run a java application? – SubSevn Jun 26 '13 at 12:19
  • 2
    @Renan: `Thread != thread` and exceptions need to be taken care of. The code above won't compile. – jlordo Jun 26 '13 at 12:21
  • it's Thread, not thread, and sleep() may throw an Exception that you must check (or re-throw from the main) – Jacopofar Jun 26 '13 at 12:22
  • possible duplicate of [How can I delay a Java program for a few seconds?](http://stackoverflow.com/questions/3342651/how-can-i-delay-a-java-program-for-a-few-seconds) – Tiago Sippert Jun 26 '13 at 12:27
  • C'mon guys let him learn, also take care about exceptions buddy, it (`Thread.sleep(xxx)`) throws InterruptedException :) –  Jul 16 '13 at 13:52

7 Answers7

3

try

try {
    for (int i=1;i<=10;i++) {
      System.out.println(i);
      Thread.sleep(1000);
    }
 } catch(InterruptedException e) {
        e.printStackTrace();
 }
Michael Shrestha
  • 2,547
  • 19
  • 30
  • Empty catch blocks make me cry. You'll have a hard time debugging when you hide the source of the errors... – jlordo Jun 26 '13 at 12:24
  • Not just that, but catching `InterruptedException` within a for-loop is broken. Just don't catch anything and let the exception interrupt the thread. – Marko Topolnik Jun 26 '13 at 12:28
  • You should put the entire for loop in a try catch block because if the thread gets interrupted your 10 second wait will be desynced and not actually 10 seconds anymore. Thus it would be pointless to continue the for loop after the first exception. – JREN Jun 26 '13 at 12:30
  • your for condition should also be i < 10 and i should start at 0. But that's just a minor detail to increase code readability, it doesn't change anything to the efficiency of the code. – JREN Jun 26 '13 at 12:34
  • 1
    i thought he was asking for count upto 10 so i started it at 1.. – Michael Shrestha Jun 26 '13 at 12:36
2

sleep() is a static method on the Thread class, there is no instance variable thread within your code. I'm assuming this throws a NullPointerExcepetion.

class OrigClass {

    public static void main(String[] args) {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(i);

                Thread.sleep(1000); // was thread.sleep(1000)
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • starting at 0 and going until i<=10 will count to 11. It won't print the 11th time, but it'll still wait 11 seconds. And you also need to put Thread.sleep in a try catch or it won't let you compile the code. – JREN Jun 26 '13 at 12:24
  • 2
    Handle the `InterruptedException` perhaps ! – AllTooSir Jun 26 '13 at 12:24
  • Letting your void main throw an exception is just yucky. You should handle the exception in your main. – JREN Jun 26 '13 at 12:28
  • @TheNewIdiot I didn't say you did, I just let you know I made the updates per your suggestion. – Kevin Bowersox Jun 26 '13 at 12:35
1

Thread class may throw exception.So put Thread.sleep(1000) in try-catch block.

public static void main (String[] args) throws InterruptedException
    {
        for(int i = 0; i<=10;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
        }
    }
Manish Doshi
  • 1,205
  • 1
  • 9
  • 17
  • Another bad advice... that's not at all how you treat `InterruptedException`. – Marko Topolnik Jun 26 '13 at 12:29
  • @Mark: Can you explain what are you asking me to do..? – Manish Doshi Jun 26 '13 at 12:34
  • Your code *swallows* the exception and continues execution. The proper thing to do is let `InterruptedException` truly interrupt the thread. In this case just adding `throws InterruptedException` to `main` would be the cleanest option. – Marko Topolnik Jun 26 '13 at 12:36
  • Yep, that's done the trick. I'm trying to learn Java on my own...in Pascal we could simply go delay(1000); and that was that... – Sam Jun 26 '13 at 12:36
  • 1
    Yea @mark.I just updated my code as you told for throws Exception rather than catching it. – Manish Doshi Jun 26 '13 at 12:39
  • That is very naughty. You should only catch exceptions that can be thrown; others are best left to function callers and even the JVM. And there is really no point in having it in the loop either as the overall timing will all be messed up after the first interruption. – Bathsheba Jun 26 '13 at 12:40
  • @Jack Smith; that's all very will but Java is being helpful here in allowing you to interrupt a sleeping thread. Strongly typed exceptions are your friends. – Bathsheba Jun 26 '13 at 12:41
  • @Bathsheba Let's get serious: in 99.9% of all introductory examples, `InterruptedException` being checked is nothing but nuisance that forces newbies into making coding errors. If it was unchecked, OP and everyone else would automatically write correct code, without even knowing what pitfalls he avoided. Therefore declaring `main(...) throws Exception` is the best way to simulate that. – Marko Topolnik Jun 26 '13 at 12:44
0

javac OrigClass.java

java OrigClass

Will compile and run it, if that's what you're asking.

SubSevn
  • 1,008
  • 2
  • 10
  • 27
0

You do it like this

try {
  for(int i = 0; i < 10; i++) {
      Thread.sleep(1000);
      System.out.println("Counter at " + i + " seconds");
  }
} catch(InterruptedException e) {
  // Thread got interrupted
}
JREN
  • 3,572
  • 3
  • 27
  • 45
  • Simpler, with better results: `public static void main(String... args) throws Exception { ... }` – Marko Topolnik Jun 26 '13 at 12:25
  • You would let your void main throw Exception? It's much better to handle the exception in your main. – JREN Jun 26 '13 at 12:28
  • 1
    And why is that, JREN? What handling did you have in mind? The default exception handler already prints the stacktrace. Do you think your `{ }` handler is superior to that? That's not called *handling* an exception; it's called *swallowing* it, and you can't go worse than that. – Marko Topolnik Jun 26 '13 at 12:30
  • Whatever is put there in comment should contain the exception handling. The question is about the Thread.sleep, not HOW the exception should be handled. The point of WHERE it should be handled is still relevant though. – JREN Jun 26 '13 at 12:32
  • 1
    Having `main` throw it is a clean, safe option, and perfect for small examples like this. Leaving an empty catch-block is giving bad example to a beginner. Anyway, I don't see where you got the categorical imperative of handling `InterruptedException`, but not, for example, `NullPointerException`. What rationale do you have for that? – Marko Topolnik Jun 26 '13 at 12:33
  • Having main throw an exception will cause your program to simply crash if your thread gets interrupted. How is that better? – JREN Jun 26 '13 at 12:37
  • No, it will cause it to cleanly exit, **exactly the same way as your proposal**. Anyway, how come you are not worrying about your program "crashing" on each and every exception, save for the one special case of `InterruptedException`? I can absolutely not fathom what rationale could stand behind such a design. – Marko Topolnik Jun 26 '13 at 12:39
0

You need an upper case 't'; i.e. write Thread.Sleep();. However I perfer using java.util.concurrent.TimeUnit.SECONDS.sleep(1); as it's clearer.

And you need to handle java.lang.InterruptedException or the code will not compile.

Putting this together write

try {
    for (int i = 0; i < 10; ++i){
        /* Print the counter then sleep for a bit
         * Perhaps this is the wrong way round?
         */
        System.out.println(i);
        java.util.concurrent.TimeUnit.SECONDS.sleep(1);
    }
} catch (final java.lang.InterruptedException e){
   // ToDo - Handle the interruption.        
}
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

If you don't want to deal with Thread.sleep() yourself, and for good reason you should avoid it, you can use the Timer and TimerTask. An example below

import java.util.Timer;
import java.util.TimerTask;

public class TimerSample {

    public static void main(String[] args) {
        TimerTask task = new TimerTask() {

            int count = 0;

            @Override
            public void run() {
                // Whenever task is run, we will print the count
                System.out.println(count);
                count++;

                // If count reaches 10, we will cancel the task                    
                if (count >= 10) {
                    cancel();
                }
            }
        };

        //Schedule a timer that executes above task every 1 second
        Timer t = new Timer();
        t.schedule(task, 0, 1000);
        return;
    }
}

More interesting use cases are described here: http://www.ibm.com/developerworks/java/library/j-schedule/index.html

Wand Maker
  • 18,476
  • 8
  • 53
  • 87