Search This Blog

Monday, September 17, 2018

How to scan the input from users in Java

You can use the Scanner class of Java. It has methods of all type one can use.

How to use?
Create the object of the Scanner class like Scanner scan = new Scanner(System.in);
You can use the below methods to get the user input
  1. public String next() | it returns the next token from the scanner.
  2. public String nextLine() | it moves the scanner position to the next line and returns the value as a string.
  3. public byte nextByte() | it scans the next token as a byte.
  4. public short nextShort() | it scans the next token as a short value.
  5. public int nextInt() | it scans the next token as an int value.
  6. public long nextLong() | it scans the next token as a long value.
  7. public float nextFloat() | it scans the next token as a float value.
  8. public double nextDouble() | it scans the next token as a double value.
Example:
  1. Scanner scan = new Scanner(System.in); //Creating object
  2. int number = scan.nextInt(); // Getting input
  3. System.out.println(number); // print the input