Java Program for User Input Using Scanner class

0

Scanner is a class that is available in java.util package, It is used to obtain the input value for primitive types and Strings. It is one of the ways to read user input in java programs. To create an object of Scanner class need to pass the predefined object System.in which consider a standard input stream.




Scanner class input methods

  • next() - Finds and returns the next string from input stream.
  • nextLine() - Return line from from input.
  • nextByte() - Return byte read from input.
  • nextShort() - Return short read from input.
  • nextInt() - Return integer read from input.
  • nextLong() - Return long read from input.
  • nextFloat() - Return float read from input.
  • nextDouble()- Return double read from input.


Example program

 

 import java.util.Scanner;

 class ScannerDemo {
 
   public static void main(String args[]) {
   
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name:");
      String name = sc.nextLine();
    
      System.out.println("Enter your age:");
      int age = sc.nextInt();
      
      System.out.println("Enter your monthly salary:");
      float salary = sc.nextFloat();

      System.out.println("Information");
      System.out.println("Name:"+name);
      System.out.println("Age:"+age);
      System.out.println("Salary:"+salary);
   }
 }


Output

Enter your name:
Shouterfolk
Enter your age:
28
Enter your monthly salary:
100000
Information
Name:Shouterfolk
Age:28
Salary:100000.0


  

Scanner class is one of the ways to read input,Java provides several other inbuilt classes for reading input from the user. For example java.io.BufferedReader, java.io.Console etc.


Code explanation:


We need to Import Scanner class at the top of your Java program. The package  import java.util.Scanner. must be use to import scanner class.The next step is create an object of Scanner class in our program Scanner sc = new Scanner(System.in);. Here sc is an Scanner class's object. Use Scanner class methods as per your data type to read input from user. Say to read integer from user use in.nextInt();, similarly use others.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !