Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Get Java input on a timer

  1. #1
    Junior Member
    Join Date
    Dec 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Get Java input on a timer

    Don't know weather the is the correct place for this question

    I want to read user input on a timer.
    so input = myClass.getInput()
    will equal to a read in input from the user (from the console)
    or if the user does not respond in 2 seconds will return "" (or throw an exeption that can be caught)

    I have tried to implement this using Threads (Timer and InputReader) and a monitor class but I can not get control flow to continue until the seconds are up regardless of weather a value is returned or not. Also my solution is very 'messy' and any solution would have to be 'neat' and clear.

    Any help would be much appreciated
    Also any solutions that don't use threads would be really great

    Thanks

    John

    P.S This the current solution but it doesn't work properly as described above
    (sourced from http://stackoverflow.com/questions/6...from-system-in)
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
     
     
    public class MyThreadTest
    {
        public static void main(String[] args)
        {
            MyThread myThread = new MyThread();
            myThread.start();
     
            try
            {
                Thread.sleep(2000);
            }
            catch(InterruptedException e)
            {
                //Do nothing
            }
     
            myThread.interrupt();
     
        }
     
        private static class MyThread extends Thread
        {       
            @Override
            public void run()
            {
                BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
                String msg;
     
                while(!isInterrupted())
                {
                    try
                    {
                        if(stdin.ready())
                        {
                            msg = stdin.readLine();
                            System.out.println("Got: " + msg);
                        }
                    }
                    catch(IOException e)
                    {
                        e.printStackTrace();
                    }
                }           
                System.out.println("Aborted.");
            }
        }
     
    }
    Last edited by helloworld922; December 19th, 2011 at 12:30 PM.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Get Java input on a timer

    Where are you getting input from? The console? A GUI component? Also, what is your current solution (i.e. code)?

  3. #3
    Junior Member
    Join Date
    Dec 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Get Java input on a timer

    Sorry I have now updated the question

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Get Java input on a timer

    Please Edit your post and wrap your code with[code=java]<YOUR CODE HERE>[/code] to get highlighting. Your unformatted code is hard to read.

  5. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Get Java input on a timer

    I remember posting a solution before which "worked", but really isn't that great.

    Here's a better solution which uses Executors and the Callable interface. Note that it returns null on a timeout, but it can easily be changed to return the empty string or even throw an Exception. Also, I used the Scanner class, but it can easily be adapted to use BufferedReaders.

    It doesn't get rid of threads completely, but it does get ride of you having to handle them manually (for the most part).

    import java.io.InputStream;
    import java.util.Scanner;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ThreadFactory;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
     
    public class TimedScanner
    {
    	public TimedScanner(InputStream input)
    	{
    		in = new Scanner(input);
    	}
     
    	private Scanner in;
    	private ExecutorService ex = Executors.newSingleThreadExecutor(new ThreadFactory()
    	{
    		@Override
    		public Thread newThread(Runnable r)
    		{
    			Thread t = new Thread(r);
    			t.setDaemon(true);
    			return t;
    		}
    	});
     
    	public static void main(String[] args)
    	{
    		TimedScanner in = new TimedScanner(System.in);
    		System.out.print("Enter your name: ");
    		try
    		{
    			String name = null;
    			if ((name = in.nextLine(5000)) == null)
    			{
    				System.out.println("Too slow!");
    			}
    			else
    			{
    				System.out.println("Hello, " + name);
    			}
    		}
    		catch (InterruptedException e)
    		{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		catch (ExecutionException e)
    		{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
     
    	public String nextLine(int timeout) throws InterruptedException, ExecutionException
    	{
    		Future<String> result = ex.submit(new Worker());
    		try
    		{
    			return result.get(timeout, TimeUnit.MILLISECONDS);
    		}
    		catch (TimeoutException e)
    		{
    			return null;
    		}
    	}
     
    	private class Worker implements Callable<String>
    	{
    		@Override
    		public String call() throws Exception
    		{
    			return in.nextLine();
    		}
    	}
    }
    Last edited by helloworld922; December 19th, 2011 at 01:58 PM.

  6. #6
    Junior Member
    Join Date
    Dec 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Get Java input on a timer

    Thanks helloworld922

    I'm sorry but I can't work out how to use your class.
    TimedScanner ts = new TimedScanner();
    String str = ts.nextLine(2000);

    Obviously I need to pass a value into the constructor TimedScanner of type InputStream but how can this be done.
    The input should be the console.

    Thanks

  7. #7
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Get Java input on a timer

    Take a look at the main method I provided. I passed System.in as the parameter.

    TimedScanner ts = new TimedScanner(System.in);

Similar Threads

  1. How to Use Timer in Java
    By neo_2010 in forum Java SE API Tutorials
    Replies: 2
    Last Post: August 6th, 2013, 09:49 AM
  2. How to create timer control in java?
    By Subhasri in forum AWT / Java Swing
    Replies: 1
    Last Post: September 27th, 2011, 12:08 AM
  3. Java dialog box is blank in 2nd attempt while using timer.
    By mocherla81 in forum AWT / Java Swing
    Replies: 1
    Last Post: January 17th, 2011, 09:49 AM
  4. How to Use Timer in Java
    By neo_2010 in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: September 1st, 2009, 12:10 PM
  5. How to Use Timer in Java
    By neo_2010 in forum Java Programming Tutorials
    Replies: 0
    Last Post: September 1st, 2009, 12:10 PM

Tags for this Thread