How to read Input thru Keyboard in Java with Example , Getting Input from Console

In java there are several ways to read input through keyboard .
1) Using the BufferedReader Class
2) Using the JOptionPane class using GUI
3) Using the Scanner class in JDK 1.5

The following example shows how to use all the above mentioned classes to get input from the console Keyboard. */




import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;
public class InputKeyBoard
{

public static void main(String args[]) throws IOException
{
String st_name = JOptionPane.showInputDialog("Enter Your Name: "); // Displays Input Dialog Box to get Input

Scanner sc = new Scanner(System.in);
System.out.println("Please enter Qualification");
String className = sc.next();

System.out.println("Please enter Mark1");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strMark1 = br.readLine();
int mark1 = Integer.parseInt(strMark1);

System.out.println("Please enter Mark2");
int mark2 = sc.nextInt();

System.out.println("Please enter Mark3");
int mark3 = sc.nextInt();

int average=(mark1+mark2+mark3)/3;

System.out.println("Name :" + st_name);
System.out.println("Class :" + className);
System.out.println("Mark1 = " + mark1 + ", Mark2= " + mark2 + ", Mark3= " + mark3 );
System.out.println("Average :" + average);

}
}


//Note : When we use Scanner Class , No need to parse integer, long , ....

Running the above program :

Output :

D:\as2\JF1>java InputKeyBoard
Please enter Qualification
MBA
Please enter Mark1
90
Please enter Mark2
93
Please enter Mark3
96
Name :John
Class :MBA
Mark1 = 90, Mark2= 93, Mark3= 96
Average :93

0 comments:

Post a Comment

 
Copyright 2011 Java Online