Sunday, August 7, 2011

Java Programming Tutorial - 6 - Getting User Input

http://verticalhorizons.in/wp-content/uploads/2011/08/JOptionPane_User_Input_In_Java.bmp

The package that needs to be imported to accept user input is java.io. The java.io package contains classes and interfaces used for input and output.
The setup:
import java.io.*; 
class GetUserInput{ }

User input classes

To get user input, use the BufferedReader and InputStreamReader classes.
  • The InputStreamReader class - reads the user's input.
  • The BufferedReader class - buffers the user's input to make it work more efficiently.
  1. package com.tctalk.myapp.java.src;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. /**
  6. * ReaduserInput.java - [This code reads the user input data from command prompt]
  7. *
  8. * @author TechCuBeTalk.com
  9. * @version 1.0
  10. */
  11. public class ReaduserInput {
  12.     public static void main(String[] args) {
  13.         //  Ask the user to enter their name
  14.         System.out.print("Please enter your name: ");
  15.         //  To read user input create a reader object
  16.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  17.         String userName = null;
  18.         //  read the user input from command prompt by readLine() method
  19.         try {
  20.             userName = br.readLine();
  21.         } catch (IOException ioExcption) {
  22.             System.out.println("IO exception occurred!");
  23.             System.exit(1);
  24.         }
  25.         System.out.println("Welcome " + userName + "!! Have a Good day!!");
  26.     }
  27. }

For more practice, here's a demo:


via[techcubetalk.com]

0 comments:

Post a Comment