Method Sleep --Newbie

I am new to java, and im currently taking a class in high school on it. It is the beginning of the year so you know that I don't know a lot.
I'm doing some experiments to help me learn more than just copying the programs my teacher gives me. So, i've done enough in turtlegraphics and now I want to get more in depth with terminalIO. I want to display stuff, and pause in between lines, but not where the user has to push enter, becuz that looks dumb. I want to use a sleep method. Ok, this means new stuff that I haven't learned yet. Could anyone help me out wiht a link to a tutorial or how I can use these sleeps. The API's are useless to newbies, they are just a bunch of what is going on's. I tried many things, and in the sun.com api, i noticed i need to do something with threads. I have some code, if some one could point me in the right direction or fix what I have wrong here it will be much appreciated. Thank you so much.
//Code:
import java.lang.*;
import TerminalIO.KeyboardReader;
public class RabbitHole {  //RabbitHole is the name of my project
     public static void main (String [] args) {
     //Use this to allow inputs
     KeyboardReader reader = new KeyboardReader();
     Thread threader = new Thread(); //Im not sure if this is correct
threader.sleep(2000); //This gives me an error
//but is where I want the 2 second sleep
System.out.print ("Hello");
//End of Code
Thanks again for any help provided.

Also, if I want to have the effect of text appearing
as if someone was typing it right them, like a very
small amont of time, x, in between every letter. I
could do:
System.out.print("H");
try {
Thread.sleep(x); }
catch(InterruptedException ie) {}
System.out.print("I");
try {
Thread.sleep(x); }
catch(InterruptedException ie) {}
Systme.out.print("!");
For this it won't matter much, but with a lot of
characters, it would look cool. Is there a simpler
way to do this? Thankyou.
StringBuffer sentence = new StringBuffer("Hello world!");
for (int i = 0; i < sentence.length(); i++) {
    System.out.print(sentence.charAt(i));
    try {
        Thread.sleep(100);
    } catch(InterruptedException ie) {}

Similar Messages

  • How to make a method sleep without affecting the responsiveness of the GUI

    Hi,
    I want to make a method sleep for a few second before executing the rest of its body. Apparently Thread.sleep(10000) doesn't do the job as it makes the GUI non-responsive.
    Any advice would be deeply appreciated.
    Thomas

    Here's an example:
    package tjacobs.ui.ex;
    import java.awt.Color;
    import javax.swing.Icon;
    import javax.swing.JLabel;
    import tjacobs.ui.util.WindowUtilities;
    * @author tjacobs
    public class Blink extends JLabel implements Runnable {
         public static final long DEFAULT_TIME_LENGTH = 1000;
         private long mTimeLength = DEFAULT_TIME_LENGTH;
         private String mLabel;
         private Icon mIcon;a
         public void run() {
              mLabel = getText();
              mIcon = getIcon();
              try {               
                   while (true) {
                        Thread.sleep(mTimeLength);
                        String current = getText();
                        if (current.equals(mLabel)) {
                             setText("");
                             setIcon(null);
                        else {
                             setText(mLabel);
                             setIcon(mIcon);
                        repaint();
              catch (InterruptedException ex) {
                   ex.printStackTrace();
              finally {
                   setText(mLabel);
                   setIcon(mIcon);
         public Blink() {
         public Blink(String arg0) {
              super(arg0);
         public Blink(Icon arg0) {
              super(arg0);
         public Blink(String arg0, int arg1) {
              super(arg0, arg1);
         public Blink(Icon arg0, int arg1) {
              super(arg0, arg1);
         public Blink(String arg0, Icon arg1, int arg2) {
              super(arg0, arg1, arg2);
         public void setBlinkTime(long time) {
              mTimeLength = time;
         public long getBlinkTime() {
              return mTimeLength;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Blink b = new Blink("Hello World");
              b.setBackground(Color.RED);
              WindowUtilities.visualize(b);
              b.setFont(b.getFont().deriveFont(24.0f));
              b.run();
    }

  • How to be able to change a variable used by an actived method?

    a JDialogBox controls the sleep time (int rate). a button listener uses this variable in thread.sleep()
    Problem:
    client cannot change rate while button listener is processing.
    How can i change my code in order to change the sleep time instantaneously while the button is pressed??
    Code:
    private int rate =300; //instance variable
    //JDialogBox listener
    private class SpeedListener implements ActionListener
    public void actionPerformed( ActionEvent event) {
    if(speedBox.isSelected())
    rate = 100;
    else rate = 300;
    //JButton listener
    private class ButtonListener implements ActionListener
    public void actionPerformed(ActionEvent e) {
    dfs();
    //dfs method calls sleep(rate) method
    //sleep method
    private void sleep(int delay)
    try {
    Thread.sleep(delay);}
    catch(InterruptedException exception) {
    System.err.println(exception.toString()); }
    }

    you need to type
    currentTemp = my AC.getTemp();because your AirConditioner.getTemp() method returns an int(1 in this case). If you just call getTemp, the program will return 1 to noone who listens. If you do this:
    currentTemp = getTemp();you should get an "unknown symbol" Error, because if you call a method from an object, you need to specify the object which "has" the method.
    Edited by: AikmanAgain on Feb 23, 2008 11:41 AM

  • Make a Thread to get sleep for a time that has decimals

    I need a Thread to get sleep for a time that has decimals, for example 3,5 miliseconds but is not possible because the Thread.sleep() admits only long. Is not other way to do it?
    Thanks

    dannyyates wrote:
    Well, there's sleep(long millis, int nanos), but to be honest if you're requirements are that tight, sleep() is probably not the right tool for you because if doesn't really guarantee any level of accuracy.That's true, the accuracy of sleep() depends rather on the underlying OS and hardware. As the docs say:
    "Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, *subject to the precision and accuracy of system timers and schedulers*. "
    Just run this simple test program, it gives interesting results:
         long start, stop;
         for (int i=0; i<100; i++) {
              start = System.nanoTime();
              try {
                   Thread.sleep(5);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              stop = System.nanoTime();
              System.out.println("The thread slept for " + (stop-start)/1000000.0 + " ms");               
         }On my Windows XP with dual core CPU I get:
    The thread slept for 5.801576 ms
    The thread slept for 5.778108 ms
    The thread slept for 6.134019 ms
    The thread slept for 5.437562 ms
    The thread slept for 6.064458 ms
    The thread slept for 5.674744 ms
    The thread slept for 15.354466 ms
    The thread slept for 5.869461 ms
    The thread slept for 5.785372 ms
    The thread slept for 5.804649 ms
    If you really need a precise timer you need either a real-time OS or a different solution, the method sleep(millis, nanos) will solve the problem without proper OS/hardware

  • I don't where do I start

    Concept
    Construct a traffic flow simulator that models cars travelling down a laneway. You may create the simulator in several stages, each one more sophisticated than the previous. In the last stage, cars travel along the laneway at various speeds, without crashing into other cars. There is also a stoplight, which alternately stops traffic and lets traffic go.
    Design Considerations
    Architecture
    We suggest that you use an architecture that has:
    1.     A driver programmer (a JApplet running in an HTML page you create and submit). Let the driver programme create the instance of the traffic simulator and start the show. Keep the driver programme simple. (See Loftus and Lewis for many examples of this sort)
    2.     The simulator classes, which include:
    o     A class representing the traffic simulator itself (including the controls for starting the simulation, and testing for synchronization (see below))
    o     A class representing the road (It keeps a list of the cars and where the cars are on the road)
    o     A class representing a car. (You will need more than one instance of this class � one for each car that is running)
    o     A class representing a stoplight (You only need one instance.)
    Responsibilities
    To make the simulation work, you will need to have cars that have a position on the road.
    �     Each car (running on its own thread) will update its position according to its current speed. It is required that you use threads.
    �     The road becomes the class that �collects� these cars. Therefore, it needs to create and keep a record of which instances of the car class exist.
    �     The traffic simulator itself creates the road, and any needed controls.
    �     The stoplight is like a car, except that it does not move (place it half way along the road), and it alternates every few seconds between �red� (when it is like a car on the road, and other cars cannot get past it) and �green� (when it is not blocking cars)
    To display the road, you might have the road draw itself, and then call on each car to draw itself on the road.
    Underlying Model
    It is a good idea to have a data structure of some kind to represent the simulation. Do not count on the picture of the road to also be the underlying model, because the picture is a complex set of graphic coordinates (many of which will have to change when a car moves).
    Instead, think more abstractly: a road is a set of positions, and a car has one of those positions. Therefore, the underlying model of the road might be:
    �     An array, each element of the array representing a position on the road. The car's current position is represented by a reference to the car placed somewhere in the array (like markers moving in a Parcheesi or Monopoly game).
    You may choose another model. Whatever model you choose, you will have a much easier time moving a car by changing its position in the underlying model, than by trying to change it directly on the graphic display.
    Threads
    Each car needs to run on its own thread. The simulator creates the instances of car, and starts its thread. The car (inside its run() method):
    �     Sleeps for a while (the faster it is going, the less time it sleeps between moves)
    �     Checks the road to see if can move forward.
    �     Moves, if it won't crash into cars or stoplights, or else reduces its speed and sleeps some more...
    Good practice: Inside the run() method, you need to have the above steps repeat over and over. Avoid using an infinite loop (e.g. while (true)) or even a loop based on a fixed number of iterations (e.g. for (... i<1000 ...) ) . Instead, have a boolean variable such as �go� and use:
    while (go) { ... }
    When �go� is true, the steps can repeat. When you are ready to stop the thread, you set �go� to false. Remember to stop your thread when the car comes to the end of the road.
    Synchronization
    You should implement synchronization, so that each car or stoplight gets to complete one attempt at changing the state of the road without being interrupted by another car or stoplight.
    Testing Synchronization
    To help us test your implementation of synchronization, add a �testsync� parameter to your HTML file and to your JApplet, which you should �get� in the init() method. If it is not present, the road behaves normally, but if it is present, the change() method of the road should sleep for 2 seconds before returning. Adding the delay means that you should be able to �see� the synchronization in action: the cars will pause, too!
    Start and End of Road
    You can make cars appear at the start of the road by having the simulator wait a random amount of time, and then create a new instance of car. When cars get to the end of the road, you can let them �disappear�. Alternatively, you can make your road circular, i.e., have the end of the road feed cars into the beginning again. It is easy to make the road circular: just make sure that in the underlying model of the road, the next element after the final one is the first element again. The use of modular arithmetic
    (index++)% myArray.length;
    can make this easy. (Of course, if your road is circular, you may have to rethink how cars start ...)
    Graphic display
    Once you have an underlying model, and the cars move along the road on the underlying model, then it is easy to draw a picture of the road with the cars on it in their current position.
    Some hints:
    �     Draw the track on a JPanel that is just for the road, the stoplight and the cars. Keep any other displays in other places.
    �     Use the repaint() method of JPanel to redraw it, invoking super.paint(g); as the first statement of the paint() method. (It is also possible to create your own draw methods() instead.)
    �     The road can be drawn as a long rectangle going horizontally across the JPanel.
    �     It is sufficient to make a rectangle to represent a top-down view of a car. To get fancier:
    o     Draw a rectangle of car colour
    o     Put a black edge around it
    o     Put a smaller black edge in the centre of it (for the top)
    o     Put the car number on the top of the car.

                         CAR1                    CAR2                     STOP
                          |                       |                         |
                          |                       |                         |
                          |                       |                         v
                          |                       |                      ======
                          |                       |                    \ |    |
                          |           BOOM        |                    -(|    |
                          |             |         |                     (|    |
                          v             |         v                     (|    |
                                        v                                |____|
                         ________      .  * .   ______                     ||
                        /    |   \      * .  * /   |  \                    ||
                  _____/_____|____\___/\/\/\/|/____|___\_____o             ||
            o     |   __              __ |  __           __  |             ||
         .     o (|__/  \____________/  #|_/  \_________/  \_|)            ||
        O  .  o  ==  \__/            \__%  *__/         \__/               ||             

  • Cannot reslove symbol class Date

    I am trying to get a clock to show the time in my program. However, when I try to compile the program a "cannot resolve symbol class Date" error appears. I can't figure out where the problem in my program is. Here is my source code. I would appreciate any help.
    import javax.swing.*;
    import java.io.*;
    import java.lang.*;
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    //import java.util.*;
    import java.math.*;
    public class store
    public static void main(String[] args)
    String dataInput;
         dataInput = JOptionPane.showInputDialog(null, "Input item data: ");
    JOptionPane.showMessageDialog(null, "" + dataInput);
    EasyReader console = new EasyReader();
    int i, j, k, inum, icom, min, nswaps; inum = 0; boolean swap = false;
    double num[] = new double[100]; double dsum, T;
         do
         System.out.println(); System.out.println("Command Menu"); System.out.println();
         System.out.println("1 = Display the data");
    System.out.println("2 = Bubble Sort the numbers");
    System.out.println("3 = Selection Sort the numbers");
    System.out.println("4 = Insertion Sort the numbers");
    System.out.println("5 = Binary Search for a number");
    System.out.println("0 = Exit the program"); System.out.println();
    System.out.print("Enter Command - ");
    icom = console.readInt(); System.out.println();
    switch (icom)
    case 1: // Display the data
                   Display(inum, num);
                   break;
    case 2: // Bubble sort
                   nswaps = 0;
                   for (i = 0; i < (inum-1); i++ )
              for (j = (i+1); j < inum; j++)
                        if (num[i] > num[j])
                                  T = num;
                             num[i] = num[j];
                             num[j] = T;
                             nswaps++;
                   System.out.println("The number of swaps was - " + nswaps);
                   Display(inum, num);
                   break;
    case 3: // Selection sort
                   nswaps = 0;
                   for (i = 0; i < inum - 1; i++) {
              min = i; swap = false;
    for (j = i + 1; j < inum; j++)
         if (num[j] < num[min]) { min = j; swap = true; }
    if (swap) {T = num[min];
              num[min] = num[i];
                        num[i] = T;
                        nswaps++;}
                   System.out.println("The number of swaps was - " + nswaps);
                   Display(inum, num);
                   break;          
    case 4: // Selection sort
                   nswaps = 0;
                   for (i = 1; i < inum; i++)
                   j = i; T = num[i];
                        while ((j > 0) && (T < num[j-1]))
              num[j] = num[j-1]; j--; nswaps++;
                   num[j] = T; nswaps++;
                   System.out.println("The number of swaps was - " + nswaps);
                   Display(inum, num);
                   break;
    case 5: // Binary Search
                   System.out.println("Your numbers will be sorted first");
                   System.out.println();
                   for (i = 1; i < inum; i++)
                   j = i; T = num[i];
                        while ((j > 0) && (T < num[j-1]))
              num[j] = num[j-1]; j--;
                   num[j] = T;
                   System.out.print("Enter the number to locate - ");
                   T = console.readDouble(); nswaps = 0; System.out.println();
                   int left = 0, right = inum, middle; k = -1;
                   while (left <= right)
                        middle = (left + right) / 2;
                        if (T > num[middle]) {left = middle + 1; nswaps++;}
                        else if (T < num[middle]) {right = middle - 1; nswaps++;}
                        else { k = middle; break; }
                   if (k == -1) System.out.println("Your number was not located in the array");
                   else System.out.println("Your number " + T + " is in position " + (k+1));
                   System.out.println();
                   System.out.println(nswaps + " comparisons were needed to search for your number");     
                   Display(inum, num);
                   break;
         } while (icom != 0);
         public static void Display(int inum, double num[])
              {     int k;
                   System.out.println();
                   System.out.println("");
                   System.out.println();
              for (k = 0; k < inum; k++)
              System.out.println((k+1) + " - " + num[k]);
         return;
    class Clock extends Thread
         //A Canvas that will display the current time on the calculator
         Canvas Time;
         //A Date object that will access the current time
         private Date now;
         //A string to hold the current time
         private String currentTime;
         //The constructor for Clock, accepting a Label as an argument
         public Clock(Canvas _Time)
              Time = Time;          //Time is passed by reference, so Time
                                       //now refers to the same Canvas
              start();               //start this thread
         //The overriden run method of this thread
         public void run()
              //while this thread exists
              while (true)
                   try
                        draw_clock();          //calls the draw_clock method
                        sleep(1000);          //puts this thread to sleep for one
                                                 //second
                   //catches an InterruptedException that the sleep() method might throw
                   catch (InterruptedException e) { suspend(); }
                   //catches a NullPointerException and suspends the thread if one occurs
                   catch (NullPointerException e) { suspend(); }
         //A method to draw the current time onto the Time Canvas on the applet
         public void draw_clock()
              try
                   //Obtains the Graphics object from the Canvas Time so that it can
                   //be manipulated directly
                   Graphics g = Time.getGraphics();
                   g.setColor(Color.gray);          //sets the color of the Graphics object
                                                      //to gray for the rectangle background
                   g.fillRect(0,0,165,25);          //fills the Canvas area with a rectangle
                                                      //starting at 0,0 coordinates of the Canvas
                                                      //and extending to the length and width
                   g.setColor(Color.orange);     //sets the color of the Graphics object
                                                      //to orange for the text color
                   get_the_time();                    //calls the get_the_time() method
                   //calls the drawString method of the Graphics object g, which will
                   //draw a string to the screen
                   //Accepts a string and two integers to represent the coordinates
                   g.drawString("Current Time - " + currentTime, 0, 17);          
              //catches a NullPointerException and suspends the thread if one occurs
              catch (NullPointerException e) { suspend(); }
         //A method to obtain the current time, accurate to the second
         public void get_the_time()
              //creates a new Date object for "now" every time this is called
              now = new Date( );
              //integers to hold the hours, minutes and seconds of the current time
              int a = now.getHours();
              int b = now.getMinutes();
              int c = now.getSeconds();
              if (a == 0) a = 12;          //if hours are zero, set them to twelve
              if (a > 12) a = a -12;     //if hours are greater than twelve, make a      
                                            //conversion to civilian time, as opposed to
                                            //24-hour time
              if ( a < 10)               //if hours are less than 10
                   //sets the currentTime string to 0, appends a's value and a
                   //colon
                   currentTime = "0" + a + ":" ;
              else
                   //otherwise set currentTime string to "a", append a colon
                   currentTime = a +":";               
              if (b < 10)                    //if minutes are less than ten
                   //append a zero to string currentTime, then append "b" and a colon
                   currentTime = currentTime + "0" + b + ":" ;
              else
                   //otherwise append "b" and a colon to currentTime string
                   currentTime = currentTime + b + ":" ;
              if (c < 10)                    //if seconds are less than ten
                   //append a zero to string currentTime, then append "c" and a colon
                   currentTime = currentTime + "0" + c ;
              else     
                   //otherwise append "c" to currentTime string
                   currentTime = currentTime + c;
    }          //end of the Clock class

    Wow.
    1) Please in future use the code tags to format code you post so that it doesn't think you have italics in your code and render it largely1 unreadable. Read this
    http://forum.java.sun.com/help.jspa?sec=formatting
    2) You commented out the import of java.util which is the problem you are complaining about.
    3) Are you planning to stick all the code you ever write into the one source file? Why is all this stuff rammed together. Yoinks.

  • Thread access

    I am new to Thread. I am doing a following call and the only thing I wanted to do here is to sleep for a second.
    101: try{
    102: Thread.currentThread().sleep(1000);
    103: }catch (InterruptedException ie) {
    104: System.out.println("InterruptedException caught");
    105: }
    When I tried to compile my code using Eclipse 2.1.0, I get a following warning message saying "The Static Method sleep(long) from the type Thread should be accessed in a static way(line 102)". What does that mean?... the code works and runs fine. I know this is just Eclipse 2.1.0 specific warning, but I am just curious if I am doing the thread call the right way. Thanks

    OK thanks I would just call it good style kind of lets you know right then and there this is a staic method this is not just from the way the method is called without having to go back and look at the method declaration, but your post made me think there might be an actual technical reason to do it.

  • Game runs fine in sun jvm, microsoft jvm causes 99% cpu usage and is SLOW

    In the microsoft JVM (my target platform) I get 2 frames per second... in the sun JVM I get at least 60.
    The strangest part, is that this only repros when iexplorer.exe is the only process running java anything... for example, if I have net beans running, I get 60 FPS in the microsoft JVM as well. That makes no sense to me.
    I have tried thread.yeild and thread.sleep in my main loop, and that didn't fix anything.

    In the microsoft JVM (my target platform) I get 2
    frames per second... in the sun JVM I get at least
    60. Don't use the MS JVM. I
    The strangest part, is that this only repros when
    iexplorer.exe is the only process running java
    anything... for example, if I have net beans running,
    I get 60 FPS in the microsoft JVM as well. That
    makes no sense to me.
    I have tried thread.yeild and thread.sleep in my main
    loop, and that didn't fix anything.About these 2 methods.
    sleep() // example in almost every book. Leaves
    // Thead on the schedule list
    yeild() // Pell mell as in no control of when it unyields.
    // prone to race/deadlock UNLESS monitored by
    // another thread that wakes up periodically.
    Tony's "Theorized" <- make the uptight acedemic sycophants happy.
    Law of the exec constant.
    "Any Thread or process *that locks the system MUST yeild controls for at
    least 20MS pre iteration."
    Why 20MS? It gives the underlying OS a little slice and is enough
    to ensure everything gets enough CPU. Every MS under 20 increases
    the deadlock potential. (*If at zero wait you get a preempted deadlock)
    You can play with this value but I have found it is pretty consistent
    across CPU speeds / hardware/
    Use a synchronized wait() in your main run method every iteration.
    Objet waitObject();
    synchronized(waitObject)
    try
       waitObject.wait(20);
    catch(InterruptedException ie)
    }wait() Removes the Thread from being scheduled.
    This iwll give IE the CPU it needs and your CPU should dro
    to around 1%.
    Hmm now how many kicked dog howls am I going to get about his message
    (T)

  • Object locks

    When does a thread release an object lock?
    Is the lock a thread holds release if the thread calls either of the methods sleep(), yeild(), or join()?
    Thanks

    When does a thread release an object lock?
    a) When you leave the synchronized block.
    b) When you call wait() on the object.
    Note in the case of b) when the thread is notifyed the thread will reaquire the monitor before proceeding.
    Is the lock a thread holds release if the thread
    calls either of the methods sleep(), yeild(), or
    join()?No.
    >
    Thanks

  • Hi when I stream video content to my Tv using Apple from my Ipad3 I find the Ipad goes to sleep after 2/3 minutes and disconects, the only way I have found to stop this is to continually tap the Ipad screen but there has to be a simpler method/ any help

    Hi when I stream video content to my Tv using Apple tv from my Ipad3 I find the Ipad goes to sleep after 2/3 minutes and disconects, the only way I have found to stop this is to continually tap the Ipad screen but there has to be a simpler method/ any help would be most welcome.

    Welcome to the Apple Community.
    Contact the developer of the Air Video app.

  • Newbie: Method should or should not have side effects

    Hi experts,
    What does it really mean when I read for the InputVerifier class that the method 'shouldYieldFocus' can have side effects but the method 'verify' should not have side effects.
    Thanks for you comments.
    tuckie

    I am but a newbie only asked to learn and maintain. The reason I ask about side effects is that the shouldYieldFocus() method is invoked twice for the same tab key event. When the tab key (or mouse click) wants to move focus to another input the current input's shouldYieldFocus() is invoked, it in turn invokes verify() which validates data returning true or false and checks to see if a warning should be issued that the data is legal but high. If the data is not high it also returns true and the focus is yielded. Also shouldYieldFocus() is only invoked once. It is when the data is high and the showConfirmDialog() is put up that I get the second shouldYieldFocus() invocation. The previous coder put in a de-bouncing mechanism and I think this is where/how the problems with the next field are created. Sometimes the next field's focusLost() is invoked without the operator making any input. The focusLost() does some fill in the blank things that are reasonable only if the operator really wanted not to fill in any data in the field.
    Back to my original point, I was wondering if the fact that the verify() method may have a dialog box put up before it returns to shouldYieldFocus() is the kind of thing that shouldn't be done - no side effects. If so then it could be the likely cause of the problem with the next field sometimes being automatically filled in as if it had received a focusLost() event.
    tuckie

  • JSF newbie question - ServletException - Method not found

    I just started learning JSF (and JSP) by following the tutorial:
    JSF for nonbelievers: Clearing the FUD about JSF
    http://www-128.ibm.com/developerworks/library/j-jsf1/
    I'm getting a ServletException and I'm not sure why. Instead of starting the tutorial over, I'd like to learn what I'm doing wrong.
    The exception is:
    exception
    javax.servlet.ServletException: Method not found: [email protected]()
    root cause
    javax.el.MethodNotFoundException: Method not found: [email protected]()In the calculator.jsp page (a simple page with two form fields), I noticed that when I type CalcBean., my IDE (NetBeans) only autocompletes the class variables and neither of the methods (add and multiply). I quickly searched and someone suggested restarting the server. This did not fix my problem. I must be doing something completely wrong or I missed something in the tutorial. If you don't mind, please read the simple files below and see if you can spot anything wrong. Please keep in mind this is my first time using JSF (and JSP for that matter). If you can suggest a better newbie tutorial, please do! Thanks
    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <context-param>
            <param-name>com.sun.faces.verifyObjects</param-name>
            <param-value>false</param-value>
        </context-param>
        <context-param>
            <param-name>com.sun.faces.validateXml</param-name>
            <param-value>true</param-value>
        </context-param>
        <context-param>
            <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
            <param-value>client</param-value>
        </context-param>
        <servlet>
            <servlet-name>Faces Servlet</servlet-name>
            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
            </servlet>
        <servlet-mapping>
            <servlet-name>Faces Servlet</servlet-name>
            <url-pattern>/faces/*</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
         <welcome-file>
                index.jsp
            </welcome-file>
        </welcome-file-list>
    </web-app>
    faces-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- =========== FULL CONFIGURATION FILE ================================== -->
    <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
      <managed-bean>
        <description>
                    The "backing file" bean that backs up the calculator webapp
                </description>
        <managed-bean-name>CalcBean</managed-bean-name>
        <managed-bean-class>secondapp.controller.CalcBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
      </managed-bean>
      <navigation-rule>
        <from-view-id>/calculator.jsp</from-view-id>
        <navigation-case>
          <from-outcome>success</from-outcome>
          <to-view-id>/results.jsp</to-view-id>
        </navigation-case>
      </navigation-rule>
    </faces-config>
    secondapp.controller.CalcBean.java
    package secondapp.controller;
    import secondapp.model.Calculator;
    * @author Jonathan
    public class CalcBean {
        private int firstNumber;
        private int secondNumber;
        private int result;
        private Calculator calculator;
        /** Creates a new instance of CalcBean */
        public CalcBean() {
            setFirstNumber(0);
            setSecondNumber(0);
            result = 0;
            setCalculator(new Calculator());
        public String add(int a, int b) {
            result = calculator.add(a,b);
            return "success";
        public String multiply(int a, int b) {
            result = calculator.multiply(a,b);
            return "success";
        // <editor-fold desc=" Accessors/Mutators ">
        public int getFirstNumber() {
            return firstNumber;
        public void setFirstNumber(int firstNumber) {
            this.firstNumber = firstNumber;
        public int getSecondNumber() {
            return secondNumber;
        public void setSecondNumber(int secondNumber) {
            this.secondNumber = secondNumber;
        public int getResult() {
            return result;
        public void setCalculator(Calculator calculator) {
            this.calculator = calculator;
        // </editor-fold>
    secondapp.model.Calculator
    package secondapp.model;
    * @author Jonathan
    public class Calculator {
        /** Creates a new instance of Calculator */
        public Calculator() {
        public int add(int a, int b) {
            return a+b;
        public int multiply(int a, int b) {
            return a*b;
    calculator.jsp
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
    <html>
        <head><title>Calculator Test</title></head>
        <body bgcolor="white">
            <h2>My Calculator</h2>
            <f:view>
                <h:form id="calcForm">
                    <h:panelGrid columns="3">
                        <h:outputLabel value="First Number" for="firstNumber" />
                        <h:inputText id="firstNumber" value="#{CalcBean.firstNumber}" required="true" />
                        <h:message for="firstNumber" />
                        <h:outputLabel value="Second Number" for="secondNumber" />
                        <h:inputText id="secondNumber" value="#{CalcBean.secondNumber}" required="true" />
                        <h:message for="secondNumber" />
                    </h:panelGrid>
                    <h:panelGroup>
                        <h:commandButton id="submitAdd" action="#{CalcBean.add}" value="Add" />
                        <h:commandButton id="submitMultiply" action="#{CalcBean.multiply}" value="Multiply" />
                    </h:panelGroup>
                </h:form>
            </f:view>
        </body>
    </html>

    In the future, please add some line breaks so I don't have to scroll horizontally to read your post.
    The problem is that the CalcBean.add/.multiply method is requiring two parameters. This method should be parameter-less. When talking about action methods, they should return String and not take any parameters.
    So, remove the parameters. You collect a firstNumber and a secondNumber from the user. These are the numbers you want to add (or multiply). Use those values (instead of the parameters) to calculate the result.
    The code changes aren't too complicated. I'd write them out for you, but you seem interested in learning (which is great by the way!). Let me know if you need more help on this.
    CowKing
    ps - I see more problems with the code, and I haven't given you all the answers. I know, I'm mean. You'll learn better if you try to fix things on your own first. I've just given you enough info to overcome the immediate issue. =)

  • Confusion using Thread.sleep() method

    I tried it in this program
    class NewThread implements Runnable {
      String name; // name of thread
      Thread t;
      NewThread(String threadname) {
        name = threadname;
        t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start(); // Start the thread
      // This is the entry point for thread.
      public void run() {
        try {
          for(int i = 5; i > 0; i--) {
            System.out.println(name + ": " + i);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
          System.out.println(name + "Interrupted");
        System.out.println(name + " exiting.");
    class MultiThreadDemo {
      public static void main(String args[]) {
        new NewThread("One"); // start threads
        new NewThread("Two");
        new NewThread("Three");
        try {
          // wait for other threads to end
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          System.out.println("Main thread Interrupted");
        System.out.println("Main thread exiting.");
    }the output is
    one: 5
    two: 5
    three 5
    delay of 1 second
    one:4
    two: 4
    three: 4
    delay of 1second
    what all i know about sleep() is that it pause the currently executing thread for specified time. hence in above program when first thread runs and prints value 5 then it should get paused for 1 second cause there is Thread.sleep(1000) after println() statement.
    and output should be
    one: 5
    delay of 1 second
    two: 5
    delay of 1 second
    three: 5
    delay of 1 second
    but this is not actually happens. may be i am wrong about Thread.sleep method() or something else.
    would you guys please clear it?
    regards
    san

    Thread.sleep() only sleeps the current thread. As each thread runs concurrently they all print concurrently and all sleep concurrently.

  • Access sleeping thread's method

    Hi,
    Situation:
    if suppose a thread is sleeping and it has class method called sendMessage() it in.
    some other class instance requires to use this sleeping thread's sendMessage() method call, will this class instance have access to the method right away or is it blocked until the sleeping thread wakes up.
    thanks

    And to take a WAG at a potential source of confusion...
    A thread of execution is an abstraction that has no direct corresponding laguage construct, and is NOT the same as a Thread object.
    A Thread allows you to ask the VM to do certain things to its corresponding thread, but that thread is not a Java object.

  • My iPhone says connect to iTunes but i synced it to a different computer and my lock/sleep button is broken so i cant turn it off. I tried letting the battery die so I could try out the iPhone recovery method however it didn t work that way either. Any he

    My iPhone says connect to iTunes but i synced it to a different computer and my lock/sleep button is broken so i cant turn it off. I tried letting the battery die so I could try out the iPhone recovery method however it didn t work that way either. Any h

    The only way out of Recovery mode is to connect to iTunes and restore. If you cannot access the computer you normally sync with, you will lose all of your content, unless you sync to iCloud. With no backup present, your content will be lost.

Maybe you are looking for