User input in Java

1.Scanner is a predefined class which is used to take user input in java.

2.Scanner class is defined inside java.util package.

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

  • nextInt():Used to read integer value from the user.
  • nextFloat():Used to read float value from the user.
  • nextDouble():Used to read double value from the user.
  • next():Used to read string value without space from the user.
  • nextLine():Used to read string value from the user.
  • nextByte():Used to read byte value from the user.
  • nextShort():Used to read short value from the user.
  • nextLong():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
Anil Singhania
Enter your rollno
205
Enter your marks
86.4
Name=Anil Singhania
Rollno=205
Marks=86.4
*/

Second way to take user input in Java

1.BufferedReader is a predefined class which is used to take user input in java.
2.It 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
*/

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. 

Try to learn something new and teach something new to other. Thanks.😊

Post a Comment

0 Comments