Java Scanner Class - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Java Scanner Class - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, March 15, 2019

Java Scanner Class

Java Scanner Class

üScanner class is used to read input from the keyboard, a file, a 
string or any source that implements the Readable or 
ReadByteChannel.

üScanner can be created for a string, an InputStream, or any 
object that implements Readable or ReadByteChannel interface.
üScanner class is under the package of java.util
üAdded in J2SE 5.

Readable Interface:

üIt is added by J2SE.
üIt is included in Java.lang.
üIt defines one method:
  int read(CharBuffer buf) throws IOException

It reads characters into buf. It returns the number of characters read or -1 if an EOF is encountered.

Taking Input from the Keyboard


üFirst, Scanner class is connected to System.in which is an object of type InputStream.

üThen, it uses its internal functions to read from System.in

Example:

Scanner test = new Scanner(System.in);

Take an input from the keyboard-1

import java.util.*;

public static void main(String[] args) {
  int value;
   System.out.print(Enter an Integer number:");  
  Scanner tmp = new Scanner(System.in);
  if(tmp.hasNextInt())
    {
  value=tmp.nextInt(); 
         System.out.println(You have entered: +value);
    }
  else
  System.out.println(Not an Integer);
}  

Taking Input from the KeyBoard-2

import java.util.*;

class input

{

  public static void main(String args[])

  {

  Scanner tmp = new Scanner(System.in);

  float i;
 
  while(tmp.hasNextFloat())

  {

       i=tmp.nextFloat();

       System.out.println("The Number: ",i);

  }

 
  }

}

No comments:

Post a Comment

Post Top Ad