Pages

JAVA INPUT STREAM


     This tutorial will show to you how to read user inputs when you creating a console applications. Most of the time in programming we need to get user inputs. So in JAVA simplest way to read user input is System.console().

   class test1
    {
        public static void main()
        {
           System.out.println("Type your name");
           String name = System.console().readLine();
           System.out.println("Your name is :"+name);
        }
    }

     You can successfully run this method in "command Line" in windows. But if you use IDE like "Eclipse", it will generate errors. 


     

Error in Eclipse..

     java.util.Scanner and System.in


     If you use IDE, then you have to use "java Scanner" and "System.in" to read user inputs. So first of all what is this? here is the small description,

     Scanner     -     The Scanner class in java.util allow read values of various types.

    System.in  -     An Input Stream, this connected to the keyboard inputs of console                                     program.


     You can read different data types using this Scanner object in java.

     import java.util.Scanner;
     class sample
    {
        public static void main(String[]args)
        {
            System.out.println("Type any word");
            Scanner input = new Scanner(System.in);
            String name = input.next();
            System.out.println("You type :"+name);
        }
    }

     If you are useing "integer" or any other variable you can change String name = input.next(); command phrase like following,

  •       int num = input.nextInt();
  •    byte num = input.nextByte();
  •    double num = input.nextDouble();

Article By - Nisal Priyanka ©