Wednesday 30 January 2013

Java program to get input from user

There are several ways to get input from the user. Here in this program we will take Scanner Class to achieve the task. 

This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in java. The import statement line should have to be in the first line the java program, and we proceed further for code. 

To access methods in Scanner class create a new scanner object as "in". Now we use a one of its method that is "next". "next" method gets the string of text that a user enters on the keyboard.

Depending upon your need use this method :

in.nextInt();

Note : It just reads the numbers, Not the end of line or anything after the number.

Here I'm using in.nextLine(); to get the String which user enters.

 import java.util.Scanner;  
 class GetInputFromUser  
 {  
 public static void main(String args[])  
 {  
 int a;  
 float b;  
 String s;  
 Scanner in = new Scanner(System.in);  
 System.out.println("Enter a string");  
 s = in.nextLine();  
 System.out.println("You entered string "+s);  
 System.out.println("Enter an integer");  
 a = in.nextInt();  
 System.out.println("You entered integer "+a);  
 System.out.println("Enter a float");  
 b = in.nextFloat();  
 System.out.println("You entered float "+b);   
 }  
 }  

7 comments:
Write comments
  1. Thank you for this fantastic post bro

    ReplyDelete
  2. Nice, thank you
    but how to read Byte or short or character

    ReplyDelete
  3. it is helpful but can you please list other input methods like, BufferedReader,console.

    🍻thanks.

    ReplyDelete
    Replies
    1. Sure, I will post those too. Thank you for suggesting here.

      Delete
  4. very well done, thanks bro.

    ReplyDelete
  5. thanks it is helpful

    ReplyDelete

Featured post

List of Universities in Karnataka offering M.Sc Computer Science

The post-graduate programme in Computer Science (M.Sc Computer Science) contains two academic years duration and having a four semesters....

Popular Posts

Copyright @ 2011-2022