Results 1 to 2 of 2

Thread: plz tell

  1. #1
    Rishabh0709 is offline Member
    Join Date
    Apr 2009
    Posts
    1
    Rep Power
    0

    Default plz tell

    Hi!
    I am new to this site.
    I am studying core java right now
    and using cmd for making prog.
    I just want to know that how to take any integer value as input??

  2. #2
    Wolf_Brother is offline Member
    Join Date
    Apr 2009
    Posts
    9
    Rep Power
    0

    Default

    You can do it using the Scanner class.

    Import the Scanner class into you project using:

    Java Code:
    import java.util.Scanner;
    Then you need to create a Scanner object and hook it up with the standard input (System.in). You do this via:


    Java Code:
    Scanner keyboard = new Scanner(System.in);
    Then to read in an int value use something along the lines of:

    Java Code:
    int userInput = keyboard.nextInt();

    Extra note:

    When you are using the scanner you can read in Strings as well. Take the following example:

    Java Code:
    String username = keyboard.nextLine();
    int userAge = keyboard.nextInt();
    String userSurname = keyboard.nextLine(); // This wont work in the way 
                                                             //  expected.
    In the small example above, userSurname will be empty. The reason for this is that after reading in an int the buffer that is used by Scanner is not cleared, and a newline character (\n) remains in there. Unforetunately the newline character symbolises the end of input, so when we try and read in the next line we reach a \n and skip right past any user input.

    So if you find yourself reading in Strings after you have read in an int then clear the buffer like so:
    Java Code:
    String username = keyboard.nextLine();
    int userAge = keyboard.nextInt();
    
    // Clear the newline character
    keyboard.nextLine();
    
    String userSurname = keyboard.nextLine();

    Hope that made sense,

    -Wolf Brother

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •