Java Input & Output Statements

aimtocode School

Scanner Class

A Scanner class is used to enable a program to read i.e. numbers and strings. Before using a Scanner class, the program must import the package import java.util.*;.

A Scanner class to create and obtain input from command window is as follows:
Scanner input=new Scanner(System.in);.

Methods

The various methods of the scanner class are as follows:

  • (i) int nextInt()
  • (ii) double nextDouble()
  • (iii) String next()
  • (iv) String nextLine()
  • (v) boolean hasNext()
  • (vi) boolean hasNextDouble

(i) int nextInt()

Returns a integer value. The default value for a field of type int().


(ii) double nextDouble()

Returns a double value. The default value for a field of type double is 0.0 .


(iii)String next()

Read individual words. i.e., the method next reads the characters until a white space character such as a space, tab or new line is encountered, then return a string.(excluding the whitespace)


(iv) String nextLine()

Read a line of text. The methods nextLine read characters typed by the user until the newline character is encountered, then return a string(excluding the new line)


(v) boolean hasNext()

Determines whether there is another word in the input. The method hasNext returns the boolean value true if there is more data; otherwise, it returns false.


(vi) boolean hasNextInt()

Determines whether the next character sequence represents a floating point.


(vii) boolean hasNextDouble()

Determines whether the next chracter sequence represents a floatingpoint.

Example 1:



Result:

Enter the value of a & b
10
20
Enter the value of pi
3.14
Enter your name
aimtocode
The value of a=10
The value of b=20
The value of pi=3.14
Name=aimtocode
aimtocode School