Getting Input From Keyboard with Java
07:30 | Author: Unknown

Hello guys.. finally i write article about java programming again.
I want to share about how to get input from keyboard in java.
Input from keyboard will be make your program become interactive, because user can input something, like name or everything.
Usually i use BufferedReader to get input from keyboard if we make program with console based.

Class BufferedReader be in package java.io.*, so we must add import java.io.* on top of your code program.
Now i wanna write an example :

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package org.wahyu.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author gepenk
*/
public class GetInput {
public static void main(String[] args){
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String firstName = "";
String lastName = "";
System.out.println("Enter Your First Name : ");
firstName = bufferedReader.readLine();
System.out.println("Enter Your Last Name");
lastName = bufferedReader.readLine();
System.out.println("Your name is " + firstName + " " +
lastName);

} catch (IOException ex) {
Logger.getLogger(GetInput.class.getName()).log(Level.SEVERE, null, ex);
}

}
}



Output for program above is

Enter Your First Name :
wahyu
Enter Your Last Name
sumartha
Your name is wahyu sumartha


Ok now i will try to explain program above.
statement BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); means we declaration variable with BufferedReader class type.
To get input from keyboard we use method bufferedReader.readLine(); that return String value. This value will be save with String data type.
Ok guy's now .. you can try it..

This entry was posted on 07:30 and is filed under . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 comments:

On 26 November 2008 at 18:39 , tediscript said...

wakakaka indonesia emang narsis...

 
On 23 December 2008 at 07:36 , Deny Prasetyo said...

Instead of BufferedReader you can user Scanner Class. That a lot of simpler.

Scanner scn = new Scanner(System.in);
String str = scn.next();
System.out.println("Result : "+str);

Or you can use Console Class. But if you use console class your program have to run in Real Console not in NetBeans output Console.

Console csl = System.console();
String str = csl.readLine();
System.out.println("Result "+str);