Read data using Scannar class

In Java, you can get input from command line arguments when you run the program. Except this there are various ways to read input from keyboard at runtime like use of Scanner class, BufferedReader class, etc.

The following program demonstrate the same. We are using Scanner class to accept a number at runtime. It is present in java.util package. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For example, the below code allows a user to read a number from System.in:
Scanner s = new Scanner(System.in);
int a = s.nextInt( );

To use Scanner class you must have to first import the java.util.Scanner package statement as shown in program. This is a simple program in which you are reading a number from keyboard and display the entered number. The Scanner class having following important methods:
  1. boolean hasNext( ) : It returns true if the scanner has another token in its input.
  2. String next( ) : If finds and returns the next complete token from the scanner.
  3. boolean nextBoolean( ) : It scans the next token of the input into a boolean value and returns that value.
  4. byte nextByte( ) : It scans the next token of the input as a byte.
  5. double nextDouble( ) : It scans the next token of the input as a double.
  6. float nextFloat( ) : It scans the next token of the input as a float.
  7. int nextInt( ) : It scans the next token of the input as an int.
  8. String nextLine( ) : Advances the scanner past the current line and returns the input that was skipped.
  9. long nextLong( ) : Scans the next token of the input as a long.
  10. short nextShort( ) : Scans the next token of the input as a short.

PROGRAM
import java.util.Scanner;

class ReadDataUsingScanner {

 public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  
  System.out.print("Enter the number :: ");
  int num = input.nextInt();
  
  System.out.println("You entered number " + num);
 }
}
OUTPUT
C:\>javac ReadDataUsingScanner.java
C:\>java ReadDataUsingScanner
Enter the number :: 9
You entered number 9

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative