User Input





Scanner Class :

  • There are so many classes to take input from the keyboard, Scanner class is one of them.

  • The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault.
    It provides many methods to read and parse various primitive values.

  • Scanner class extends Object class and implements Iterator and Closeable interfaces.


Commonly used methods of Scanner class :

There are so many methods available in Scanner class.

Here is a list of commonly used Scanner class methods:

MethodDescription
next()to read String
nextLine()to read String including space
nextByte()to read byte value.
nextShort()to read short value.
nextInt()to read int value.
nextLong()to read long value.
nextFloat()to read float value.
nextDouble()to read double value.
nextBoolean()to read boolean value.

Before using these methods you have to create an object of Scanner class.

Steps to create object of Scanner class :

  1. import the class :
    import java.util.Scanner;
  2. create the object where-ever you required :
    Scanner sc = new Scanner(System.in)
    This object will read input from keyboard.
  3. To take input call the method accordingly :
    e.g. Let suppose you want to take input type of int then
    int n = sc.nextInt();
    for String
    String name = sc.next();
         or
    String name = sc.nextLine();

Example :

Read the int, string and double value as an input:
import java.util.Scanner;  
class ScannerDemo
{  
 public static void main(String args[])
 {  
  Scanner sc=new Scanner(System.in);  
     
  System.out.print("Enter ID:");  
  int id=sc.nextInt();  
  System.out.print("Enter Name:");  
  String name=sc.next();  
  System.out.print("Enter Salary:");  
  double sal=sc.nextDouble();
  System.out.println("----------") 
  System.out.println("ID:"+id);
  System.out.println("Name:"+name);
  System.out.println("Salary:"+sal);  
  sc.close();  
 }  
}          
Enter ID:123
Enter Name:Ayan
Enter Salary:20000
----------
ID:123
Name:Ayan
Salary:20000.0

Next topic is Java-oop-concepts




 



Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in



CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved