User Inuput In JAVA programming Hands on coding

 User input in Java

In this article let's see how to take input from the users.


1.Scanner is the predefined class that can be used to take user input in java.

2.Scanner class can be defined inside the java.util package.

3.The scanner class consists of many function to take user input which is given below.


  • nextInt(): This can be used to read integer value from the user.
  • nextFloat():This is used to read float value from the user.
  • nextDouble():This is used to read double value from the user.
  • next():This is used to read string value without space from the user.
  • nextLine():This is used to read string value from the user.
  • nextByte():This is used to read byte value from the user.
  • nextShort():This is used to read short value from the user.
  • nextLong():This is used to read long value from the user.


Example

 //importing the package   
 import java.util.Scanner;   
 class Easy   
 {   
   public static void main(String[] args)   
   {    
    //creating the instance of class Scanner   
    Scanner obj=new Scanner(System.in);   
    String name;   
    int rollno;   
    float marks;   
    System.out.println("Enter your name");   
    name=obj.nextLine();    //taking string input   
    System.out.println("Enter your rollno");   
    rollno=obj.nextInt();    //taking integer input   
    System.out.println("Enter your marks");   
    marks=obj.nextFloat();   //taking float input //printing the output   
    System.out.println("Name="+name);   
    System.out.println("Rollno="+rollno);   
    System.out.println("Marks="+marks);   
  }   
 }   


### Output ###  

Enter your name: Raju Sunagar 

Enter your rollno: 205  

Enter your marks: 86.4  

Name= Raju Sunagar

Rollno=205  

Marks=86.4  

 
 

 Let's see second way to take the user input in Java.

  • BufferedReader is the predefined class that can be used to take user input in java.
  • This is defined inside the java.io package.
 //importing the package   
 import java.io.BufferedReader;   
 import java.io.InputStreamReader;   
 class Easy   
 {   
   public static void main(String[] args)   
   {   
    //creating the instance of class BufferedReader   
    BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));   
    String name;           
      try {   
    System.out.println("Enter your name");   
    name=reader.readLine();   //taking string input   
    System.out.println("Name="+name);   
         } catch (Exception e) {   
         }   
   }   
 }   



/ ### Output ###  

Enter your name Lucy Martin Name=Lucy Martin  


This is regarding user input in java.


 For Videos Join Our Youtube Channel: Join Now


Thank you!