No announcement
 

Reading Input

Till yet we have hardcoded values for variables in all of the examples. In real world applications we are bound to take certain input from user (or other system) and operate on the given input. Majority of the input is handled as part of GUI, but we will be doing this using the console.

To read input from the console we have to first construct scanner attached to system input stream System.in.

Example:

ReadingInputDemo.java

package com.codingnous.tutorial;

import java.util.Scanner;

public class ReadingInputDemo {

	public static void main(String[] args) {

		// Construct scanner.
		Scanner s = new Scanner(System.in);

		// Two variables for storing input.
		String message;
		int number;

		System.out.print("Enter your message: ");

		// Read string from console.
		message = s.nextLine();

		// Display the input string.
		System.out.println("You entered: " + message);

		System.out.print("Enter a number: ");

		// Read number from console.
		number = s.nextInt();

		// Display the input.
		System.out.println("You entered: " + number);

	}
}

Output
Enter your message: hey there! You entered: hey there! Enter a number: 20 You entered: 20