Wednesday 9 May 2012

Get user input in Java

This Java program prompts the user to enter the name by using System.out.print() method to keep the cursor on the same line. Then using the System.in object, along with the InputstreamReader and BufferedReader classes the user input is read. The br.readline() method reads the name from the command line. After pressing the enter key, you will get the user input.



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import java.io.*;

public class GetUserInput {
 public static void main(String[] args) {
  System.out.print("Enter your name and press Enter: ");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String name = null;
  try {
   name = br.readLine();
  } catch (IOException e) {
   System.out.println("Error!");
   System.exit(1);
  }
  System.out.println("Your name is " + name);
 }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...