Thursday, 26 March 2020

Read input using Scanner

Scanner is used to read read data from console, and can able to parse primitive types and strings using regular expressions.

For example, below snippet reads an integer from console.
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();

'nextLine()' method is used to read a string.
String name = scanner.nextLine();

Similarly Scanner provides following methods to read respective type of data.
         nextByte()
         nextShort()
         nextInt()
         nextLong()
         nextFloat()
         nextDouble()
         nextBoolean()
         nextBigDecimal()
         nextBigInteger()

App.java
package com.sample.app;

import java.util.Scanner;

public class App {

 public static void main(String args[]) {
  Scanner scanner = new Scanner(System.in);

  System.out.println("Enter your name : ");
  String name = scanner.nextLine();

  System.out.println("Enter your age : ");
  int age = scanner.nextInt();

  System.out.println("Enter your height : ");
  double height = scanner.nextDouble();

  System.out.println("Name : " + name);
  System.out.println("Age : " + age);
  System.out.println("Height : " + height);

 }

}

Output
Enter your name :
Rama
Enter your age :
31
Enter your height :
5.7
Name : Rama
Age : 31
Height : 5.7

You may like

No comments:

Post a Comment