Monday, April 19, 2010

Getting Keyboard Inputs II


In previous method for getting keyboard inputs we used buffered readers and input stream readers. There is a special class called Scanner available in java.util package which can be used to get keyboard inputs. Using a Scanner object we can read converted values directly into our program which means we haven't to convert read values explicitly. Scanner class be used to perform many other tasks. Lets see a simple Java program to understand its usage.

//© learnjavaapi.blogspot.com  
import java.util.Scanner;
class ScannerDemo{
 public static void main(String args[]){
  int num1;
  float num2,tot;
  String name;
  Scanner scn=new Scanner(System.in);
  System.out.print("Enter your name \t: " );
  name=scn.nextLine();
  System.out.print("Enter a Float value  \t: " );
  num2=scn.nextFloat();
  System.out.print("Enter an Integer value \t: " );
  num1=scn.nextInt();
  tot=num1+num2;
  System.out.println("Hi "+name+" total is \t: "+ tot );
 }
}

Output :

In above example I have used the created Scanner object to read three different data. String,int and float. See the java documentation for more details about Scanner class.
Class : Scanner
Since : Java 1.5
Scanner

0 comments:

Post a Comment

Stats

ලාංකීය සිතුවිලි

lankeeya sithuwili

Blog Catalogs

 

Let's Learn Java API. Copyright 2010 All Rights Reserved