How To Get Input From User in Java
How To Get Input From User in Java
Java
Java Scanner Class
Scanner sc=new Scanner(System.in);
Methods of Java Scanner Class
Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
String nextLine() Advances this scanner past the current line.
boolean nextBoolean() It is used to scan the next token of the input into a boolean value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.
BigInteger nextBigInteger() It is used to scan the next token of the input as a BigInteger.
BigDecimal nextBigDecimal() It is used to scan the next token of the input as a BigDecimal.
Example of integer input from user
1.import java.util.*;
2.class UserInputDemo
3.{
4.public static void main(String[] args)
5.{
6.Scanner sc= new Scanner(System.in); //System.in is a standard input stream
7.System.out.print("Enter first number- ");
8.int a= sc.nextInt();
9.System.out.print("Enter second number- ");
10.int b= sc.nextInt();
11.System.out.print("Enter third number- ");
12.int c= sc.nextInt();
13.int d=a+b+c;
14.System.out.println("Total= " +d);
15.}
16.}
Example of String Input from user
1.import java.util.*;
2.class UserInputDemo1
3.{
4.public static void main(String[] args)
5.{
6.Scanner sc= new Scanner(System.in); //System.in is a standard input stream
7.System.out.print("Enter a string: ");
8.String str= sc.nextLine(); //reads string
9.System.out.print("You have entered: "+str);
10.}
11.}