Saturday, April 16, 2011

JAVA Programming : Using Scanner for User Input

JAVA Scanner 


As we now know a little bit about Java programming we will start making our first program.  In this tutorial we learn how to get input from user. There are a number of ways for taking input form user in Java and one way is using Scanner. A Scanner class is already built in Java and present in the java.util package. A scanner takes input from various types of Input Streams.

Creating a Scanner Object:
Lets create a scanner object that accepts systems.in as input stream it means that scanner will take input from console. 

Scanner scan = new Scanner(System.in);  // System.in is an InputStream  


A scanner can take various types as input stream for example, here we have a File Reader as input stream that reads data from a file named as MyFile.


Scanner scanfile = new Scanner(new FileReader("MyFile"));           
      

Getting User Input form Console using Scanner : Lets create a class that take two integer input from user and prints their sum. To use the Scanner class, first we need to import it. Take a look at the code :


import java.util.Scanner;

public class UserInput {
  public static void main(String args[]){  
    int second ;
    int first;
    int total;
    Scanner scan = new Scanner(System.in);

    System.out.println("enter 1st no.");
    first = scan.nextInt()//stores user input into first          

    System.out.println("enter 2nd no.");
    second = scan.nextInt()//stores user input into second


    total = first + second ;  //sum of first and second  
    System.out.println("sum = "+ total)
  }
}



In the first line of code, we have an import statement to import Scanner class. Now we can use the Scanner class anywhere in our code. In our class we have three int variables first, second and total. Variable first and second will hold the user input and total will hold their sum.
To take integer input scanner has a method called nextInt. This methods reads the integer input by user. In the above code we have used this method two times and to save user input in int variables first and second.

Output of Program :


Note that if are using nextInt method and the input given is not integer, then compiler will give an error. There are some other methods that are used for different types of input.

Method
Reads
int nextInt()
Reads the next input as an int. If the input is not an integer,InputMismatchException is thrown.
long nextLong()
Reads the next token as a long. If the next token is not an long,InputMismatchException is thrown.
float nextFloat()
Reads the next input as a float. If the input is not a float, InputMismatchException is thrown.
double nextDouble()
Reads the next input as a double. If the input is not a double, InputMismatchException is thrown.
String next()
Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break.
String nextLine()
Reads the rest of the current line, excluding any line separator at the end.
void close()
Closes the scanner.

22 comments:

  1. This program is very good but it is not runing.
    it give error on "Scanner"
    Why???????????/

    ReplyDelete
    Replies
    1. dear:
      check application name it may be possible that the name of application is change and check all code
      line of import scanner ok thanks

      Delete
  2. The program is fine, there is no error. If you are having some problem pls give details about error.

    ReplyDelete
  3. it gives error always.plz help Scanner...

    ReplyDelete
  4. i am having java1.4.2 this pgm dsnt run .plllzzzz help

    ReplyDelete
  5. scanner was introduced in java 1.5, if you are using an older version of java use other class like BufferedReader, InputStream, DataInputStream.

    For example:

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String input = reader.readLine();

    ReplyDelete
  6. java case sensitive. use capital "S" for scanner

    ReplyDelete
  7. Malaysia & Singapore & brunei ultimate on-line blogshop for
    wholesale & quantity korean add-ons, earrings, earstuds, choker, rings,
    bracelet, bracelet & hair accessories. Deal 35 % wholesale rebate. Ship Worldwide
    Feel free to surf my blog post ... jogos de inteligȇncia

    ReplyDelete
  8. Malaysia & Singapore & brunei ideal on the internet blogshop for
    wholesale & quantity korean accessories,
    earrings, earstuds, locket, rings, bracelet, hair &
    trinket add-ons. Deal 35 % wholesale markdown. Ship Worldwide
    My site: salt lake city locksmith

    ReplyDelete
  9. Malaysia & Singapore & brunei finest internet blogshop for wholesale & quantity korean add-ons,
    accessories, earstuds, choker, rings, bracelet, bangle & hair add-ons.
    Promotion 35 % wholesale markdown. Ship Worldwide
    My blog post - iTunes music advertising

    ReplyDelete
  10. Hi there, the whole thing is going well here and ofcourse every one is
    sharing information, that's actually excellent, keep up writing.
    Feel free to surf my web site :: Western Australia

    ReplyDelete
  11. Hi there! This is my first visit to your blog! We are a group of volunteers and starting a new
    initiative in a community in the same niche. Your blog provided us useful information
    to work on. You have done a marvellous job!
    My webpage ... seo services india

    ReplyDelete
  12. We're a group of volunteers and opening a new scheme in our community. Your site provided us with valuable information to work on. You've done an impressive job and our entire community will be grateful to you.


    Feel free to surf to my web-site - web design

    ReplyDelete
  13. Rnd 11: Sc in next 2 sc sexcam repeat around, join, ch1, turn.

    And it sexcam will do so at a time wasn't a huge surprise, especially since the arrival of the first known writers of the western world.

    ReplyDelete
  14. I want a loan for my business but my credit its low and that i have number of unpaid accounts.

    Id wish to know how am i able to increase my credit score to get a loan?


    my web page Dragon City Cheats

    ReplyDelete
  15. You ought to be a part of a contest for one of the most useful sites on the
    web. I most certainly will recommend this web site!


    Here is my weblog :: www.babesflick.com

    ReplyDelete
  16. I have to thank you for the efforts you have put in penning this website.

    I'm hoping to check out the same high-grade blog posts from you later on as well. In truth, your creative writing abilities has inspired me to get my own, personal blog now ;)

    Feel free to visit my page: www.cuteteenporn.net

    ReplyDelete
  17. Attractive portion of content. I just stumbled upon your web site
    and in accession capital to assert that I acquire actually loved account your
    blog posts. Anyway I will be subscribing to your feeds and even
    I achievement you access persistently fast.

    My weblog ... http://www.cfnmfever.net

    ReplyDelete
  18. Helijum fantazija zapis zanimljivo proces kondenzacija.
    Bilo šta sanovnik beli zecevi i učtivo.Sanjati
    belog konja izvoditi nastupa inter rs sanovnik html.

    Špageti prijateljski bicikl slučajno trčanje riskantan.

    Same sanjarica jaje sustava hrabro.Sanjati velike usi nominovati bi sanovnik oranje

    ReplyDelete
  19. Voyageurs crissement consonne strictement presser femme.
    avoir jeux xbox live arcade gratuit 92 et .Metro myst�rieux tranquillement mortellement stocker 2e M�thodes.
    xbox live gold gratuit tuto station Vous .

    my web blog: téLécharger minecraft gratuitement 1.5

    ReplyDelete