FAQ

Java

JSP

Servlet


Advertisement



How to Read Input from Console in Java?

"I have an small console Java application and how to read input values from my keyboard?". You may have the same question when you read this FAQ.

The classes in Java I/O package provide ways to receive input stream from console. For example,

import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
import java.text.ParseException;

public class ConsoleInputExample {

public static void main(String[] args) {

BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
df.setLenient(false);

try {
do {
System.out.print("ENTER DATE STRING (mm/dd/yyyy or 'q') : ");
String dateString = reader.readLine();
if (dateString != null) dateString = dateString.trim();
if (dateString == null || dateString.length()== 0)
continue;
if (dateString.equalsIgnoreCase("Q"))
break;

// Parse the date
try {
Date date = df.parse(dateString);
System.out.println("Original string: " + dateString);
System.out.println("Parsed date : " + date.toString());
System.out.println();
}
catch(ParseException pe) {
System.out.println("ERROR: could not parse date in string \""
+ dateString + "\"");
}

} while (true);
}
catch(Exception e) {
;
}
}
}

In Java 5.0, the new java.util.Scanner class is a greater feature which simplifies console applications in a standardized way. This class enable us to read string, integer of byte, long, short, int type, float, and double  in console application.

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.text.ParseException;

public class ConsoleInputExample {

public static void main(String[] args) {

Scanner scanner= new Scanner(System.in);
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
df.setLenient(false);

try {
do {
System.out.print("ENTER DATE STRING (mm/dd/yyyy or 'q') : ");
String dateString = scanner.next();
if (dateString != null) dateString = dateString.trim();
if (dateString == null || dateString.length()== 0)
continue;
if (dateString.equalsIgnoreCase("Q"))
break;

// Parse the date
try {
Date date = df.parse(dateString);
System.out.println("Original string: " + dateString);
System.out.println("Parsed date : " + date.toString());
System.out.println();
}
catch(ParseException pe) {
System.out.println("ERROR: could not parse date in string \""
+ dateString + "\"");
}

} while (true);
}
catch(Exception e) {
;
}
}
}


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |