Scanner Class in Java


The following is how to properly use the java.util.Scanner class to interactively read user input from System.in correctly( sometimes referred to as stdin, especially in C, C++ and other languages as well as in Unix and Linux). It idiomatically demonstrates the most common things that are requested to be done.

The Scanner class is used to read Java user input. Scanner is part of the java.util package, so it can be imported without downloading any external libraries. Scanner reads text from standard input and returns it to a program. Once the Scanner class is imported into the Java program, you can use it to read the input of various data types. Depending on whether you want to read the input from standard input and output.

This Java program demonstrates the usage of the Scanner class to get user input from the console.

  • In this program, we first import the Scanner class from the java.util package. We then declare a Scanner object in to read input from the console.
  • We declare three float variables a, b, and c. We then prompt the user to enter two numbers using the System.out.println() method.
  • We use the in.nextFloat() method to read the user input and assign it to variables a and b. We then use the formula a^2+b^2+2ab to calculate the value of c.
  • Finally, we print the value of c using the System.out.println() method.

Source Code

import java.util.Scanner;
 
public class getting_inputs {
    public static void main(String args[])
    {
        //a2+b2+2ab
        Scanner in =new Scanner(System.in);
        //int a,b,c;
        float a,b,c;
        System.out.println("Enter 2 Nos : ");
        //a=in.nextInt();
       // b=in.nextInt();
        a=in.nextFloat();
        b=in.nextFloat();
        c=(a*a)+(b*b)+(2*a*b);
        System.out.println("Result : "+c);
 
    }
}
/*
in.nextInt();
in.nextFloat();
in.nextDouble();
in.next();
in.nextLine();
 */

Output

Enter 2 Nos :
12
34
Result : 2116
Enter 2 Nos :
2.4
3.2
Result : 31.36
To download raw file Click Here

Basic Programs