Latest News: How to Take Input in Java Using Scanner - How to Take Input From a User in Java - How to Take String Input In Java Using Scanner Class

How to Take Input in Java Using Scanner - How to Take Input From a User in Java - How to Take String Input In Java Using Scanner Class


In the Java program to get input from a user, we are using the Scanner class. The program asks the user to enter an integer, a floating-point number, and a string, and we print them on the screen. Scanner class is present in "java.util.Scanner" package, so we import this package into our program. We create an object of the class to use its methods.

Scanner p = new Scanner(System.in);

Here, p is the name of the object, the new keyword is used to allocate memory, and System.in is the input stream. Our program uses the following three methods:

1) nextInt to input an integer
2) nextFloat to input a floating-point number
3) nextLine to input a string

import java.util.Scanner;

class Input
{
   public static void main(String args[])
   {
      int a;
      float b;
      String s;
     
      Scanner in = new Scanner(System.in);
     
      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);  
   
      System.out.println("Enter a string");
      s = in.nextLine();
      System.out.println("You entered string " + s);
   }
}

Popular Posts

MyMarket