Tuesday, July 13, 2021

How to read User Input from Console in Java? Scanner Example

Apart from reading files, Scanner can also read user input from Console in Java. Just like in the case of reading files, we have provided File as a source for scanning, We need to provide System.in as a source to scan for user input in Console. Once you created and initialized java.util.Scanner, you can use its various read method to read input from users. If you want to read String, you can use nextLine(), if you want to read integer numbers, you can use nextInt(). 

Subsequently you can use nextFloat() to read float input, nextDouble() to read double input etc. Scanner class also allows you to define your own pattern and scan for that.


Reading User Input using Scanner in Java - Example

Let's see a complete code example of reading user input using the Scanner class. In this Java program, we are reading User Input in form of String using Scanner's nextLine() method and numbers particular integer using nextInt() method of Scanner. 

The scanner is created by passing System.in  which is an InputStream as a source which means it will scan input console for data. Check out these free Java Programming courses to learn more about Scanner and other fundamental Java classes. 

How to read User Input from Console in Java? Scanner Example


And, here is our complete Java program to demonstrate how to read user input from the command prompt using the Scanner class in Java. 

How to read user input using Scanner in Java with Example/**
 *
 * Java program to read input from the console using Scanner in Java
 * We pass System.in as source to Scanner which then scans Console for user input
 * @author
 */

public class UserInputExample {

    public static void main(String args[]) {
 
        //Creating Scanner instance to scan console for User input
        Scanner console = new Scanner(System.in);
   
        System.out.println("System is ready to accept input, please enter name : ");
        String name = console.nextLine();
        System.out.println("Hi " + name + ", Can you enter an int number now?");
        int number = console.nextInt();
        System.out.println("You have entered : " + number);
        System.out.println("Thank you");
     
    }  
 
}

Output:
The system is ready to accept input, please enter the name :
John
Hi John, Can you enter an int number now?
56
You have entered: 56
Thank you

That's all on How to read user input using Scanner in Java program. The scanner allows you to read various types of input directly from the User without extra conversion e.g. you can read int, float, long, double, or String directly.


Other Java tutorials from java67

3 comments:

  1. Can we get numbers as input through console? I have a program which takes two numbers and check if second number is factor of first number, but I heard we can only pass String as input through console. Please help

    ReplyDelete
    Replies
    1. USERINPUT
      package oop0528;

      import java.util.Scanner;

      public class User_Input {
      Scanner _reader;

      public User_Input() {
      this._reader = new Scanner(System.in);
      }

      public void Start( HandleShape hs ) {
      String sCommand ;
      sCommand = this._reader.nextLine() ;
      while ( Continue( sCommand ) ) {
      if ( !HandleCommand( sCommand, hs ) ) System.out.println("invalid command!!");
      } // while
      } // Start()

      public void End() {

      } // End

      private boolean Continue( String sCommand ) {
      sCommand = sCommand.toLowerCase() ;
      if ( sCommand.equals("quit") ) return false ;
      else return true ;
      } // Continue()

      private boolean HandleCommand( String sCommand, HandleShape hs ) {
      if ( sCommand.equals("circle") ) {
      hs.Add("circle");
      return true ;
      } // if
      else if ( sCommand.equals("square") ) {
      hs.Add("square");
      return true ;
      } // if


      return false;

      } // HandleCommand()

      }


      SQUARE
      /*
      * To change this license header, choose License Headers in Project Properties.
      * To change this template file, choose Tools | Templates
      * and open the template in the editor.
      */

      package oop0528;

      /**
      *
      * @author user
      */
      public class Square extends Shape {
      private double _dHeight ;
      private double _dLength ;

      @Override
      double GetArea() {
      return this._dHeight * this._dLength ;
      }

      @Override
      double GetPerimeter() {
      return ( this._dHeight + this._dLength ) * 2 ;
      }

      public double GetHeight() {
      return this._dHeight ;
      }

      public double GetLength() {
      return this._dLength ;
      }

      }

      CIRCLE
      /*
      * To change this license header, choose License Headers in Project Properties.
      * To change this template file, choose Tools | Templates
      * and open the template in the editor.
      */

      package oop0528;

      /**
      *
      * @author user
      */
      public class Circle extends Shape {
      private double _dRadius ;

      @Override
      double GetArea() {
      return this._dRadius * this._dRadius * Math.PI ;
      }

      @Override
      double GetPerimeter() {
      return this._dRadius * 2 * Math.PI ;
      }

      public double GetRadius() {
      return this._dRadius ;
      }

      }

      SHAPE
      /*
      * To change this license header, choose License Headers in Project Properties.
      * To change this template file, choose Tools | Templates
      * and open the template in the editor.
      */

      package oop0528;

      /**
      *
      * @author user
      */
      public abstract class Shape {

      abstract double GetArea() ;
      abstract double GetPerimeter() ;

      }

      /*
      * To change this license header, choose License Headers in Project Properties.
      * To change this template file, choose Tools | Templates
      * and open the template in the editor.
      */

      HANDLESHAPE

      package oop0528;

      import java.util.ArrayList;

      /**
      *
      * @author user
      */
      public class HandleShape {
      private ArrayList _allShape ;

      public HandleShape() {
      this._allShape = new ArrayList() ;
      }

      public boolean Add( String type ) {
      return false;

      } // Add()

      public double TotalArea() {
      double total = 0 ;
      for ( Shape s : this._allShape ) {
      total += s.GetArea() ;
      } // for

      return total ;
      } // TotalArea()

      }

      MAIN

      /*
      * To change this license header, choose License Headers in Project Properties.
      * To change this template file, choose Tools | Templates
      * and open the template in the editor.
      */

      package oop0528;

      /**
      *
      * @author user
      */
      public class Oop0528 {

      /**
      * @param args the command line arguments
      */
      public static void main(String[] args) {
      // TODO code application logic here

      User_Input ui = new User_Input() ;
      HandleShape hs = new HandleShape() ;
      ui.Start( hs );
      }

      }

      Delete
    2. use
      Integer.parseInt(String s)

      Parses the string argument as a signed decimal integer.

      Delete

Feel free to comment, ask questions if you have any doubt.