How to read input from user during runtime?

How to read input from user during runtime?

Postby Kishan » Fri Feb 01, 2013 5:40 am

How to read input from user during runtime?
Kishan
 
Posts: 191
Joined: Tue Jan 29, 2013 4:21 am

Re: How to read input from user during runtime?

Postby Kishan » Thu Feb 07, 2013 6:13 am

Code: Select all
package javatrng.examples.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class RuntimeInputExample {

   public static void main(String[] args) {
      BufferedReader is = null;
      
      try {
         is = new BufferedReader(new InputStreamReader(System.in));
         String line = null;
         int i = 0;
         while(true) {
            System.out.println("Enter Text (for stop enter \"quit\"): ");
            line = is.readLine();
            System.out.println("Line no# "+ (++i) + ": " + line);
            if("quit".equalsIgnoreCase(line)) {
               break;
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if(is != null) {
            try {
               is.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
}
Kishan
 
Posts: 191
Joined: Tue Jan 29, 2013 4:21 am

Re: How to read input from user during runtime?

Postby Rose » Thu Feb 07, 2013 5:21 pm

We can achieve same thing with Java's Scanner class
eg
Scanner scanner = new Scanner (System.in);
System.out.println("Please provide Input then Enter button:");
printMe(scanner);
System.out.println("\n exit");

public static <T> void printMe(Scanner x){
String y = x.nextLine();
System.out.printf("Your input :%s", y);
}
Rose
 
Posts: 20
Joined: Tue Jan 29, 2013 5:16 am

Re: How to read input from user during runtime?

Postby Kishan » Fri Feb 08, 2013 1:56 am

You are right. This class was added from JDK 1.5 onwards. Main intent for this is parsing text.
Kishan
 
Posts: 191
Joined: Tue Jan 29, 2013 4:21 am


Return to Core Java

Who is online

Users browsing this forum: No registered users and 1 guest

cron