How to take input from user in Java using Scanner
One of the strengths of
Java is the huge libraries of code available to you. This is code that has been
written to do specific jobs. All you need to do is to reference which library
you want to use, and then call a method into action.
One really useful class
that handles input from a user is called the Scanner class.
The Scanner class can be found in the java.util library. To
use the Scanner class, you need to reference it in your code. This is done with
the keyword import.
import java.util.Scanner;
We first create an
object of Scanner class and then we use the methods of Scanner class. Consider
the statement
Scanner a = new Scanner(System.in);
Here Scanner is the
class name, a is the name of object, new keyword is used to allocate the memory
and System.in is the input stream.
Following methods of
Scanner class are used in the program below :-
1.
nextInt() to input an
integer
2.
nextFloat() to input a
float
3.
nextLine() to input a string
Example:
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int i;
float f;
String s;
Scanner in = new
Scanner(System.in);
System.out.print("Enter
a string: ");
s = in.nextLine();
System.out.print("Enter
an integer: ");
i = in.nextInt();
System.out.print("Enter
a float: ");
f = in.nextFloat();
System.out.println("You
entered string: "+s);
System.out.println("You
entered integer: "+i);
System.out.println("You
entered float: "+f);
}
}
Output:
Comments
Post a Comment