Input in JAVA

Input in JAVA

There are multiple ways to take input in java. One of the method is using Scanner Class. It is the class from java.util package. There are some reasons to use Scanner Class in java, as :

  1. It is the simplest way to take input from the user.
  2. It can take input from users in primitive data types like int, float, double, char, etc.
  3. A constructor from Scanner class is used with an argument System.in to take input from user, where ” System ” is a class and “in ” is an input stream.
  4. It breaks the input into tokens using whitespace

Some of the methods that are used in Scanner class are as follows

  1. nextInt() : It scans the next token of the input as an Int.
  2. nextByte() : It scans the next token of the input as a byte.
  3. nextShort() : It scans the next token of the input as short
  4. next() : It is used to read next string value from the keyboard.
  5. nextLine() : It is used to get the input string that was skipped of the Scanner object.
  6. nextDouble() : It scans the next token of the input as double
  7. nextFloat(): It scans the next token of the input as float
  8. nextBoolean() : It scans the next token of the input as boolean
  9. next().charAt(0) – returns a single character.

Sometimes while using next and nextLine(), there might occur a problem where all the value that must be taken in any string is not accepted, because it past the current line and returns the input that was skipped.

In such cases the function prints the rest of the current line, leaving out the line separator at the end. The next is set to after the line separator. It searches for line separator and skips if no line separator is present. And the best solution for such a problem is to use ” next()” to maintain whitespace.

import java.util.Scanner;
public class TestOne {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // sc is the object of scanner class
        // String input
        System.out.print("Enter name : ");
        String name = sc.nextLine();
        // Character input
        System.out.println("Enter gender : ");
        char gender = sc.next().charAt(0);
        // Numerical data input
        System.out.println("Enter age : ");
        int age = sc.nextInt();
        System.out.println("Enter phone : ");
        long mobileNo = sc.nextLong();
        // Print the values to check if the input was correctly obtained.
        System.out.println("Name: "+name);
        System.out.println("Gender: "+gender);
        System.out.println("Age: "+age);
        System.out.println("Mobile Number: "+mobileNo);
    }
}

And the output is seen as

Share this on facebook

Subscribe to our Youtube Channel

Leave a comment

Your email address will not be published. Required fields are marked *