C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

Unexpected Behaviour of Standard Java Input and Output through Scanner Class

Submitted by Mayank Singh, on June 05, 2017

Learn: Java Scanner Class, their methods and their unexpected behaviour. This article will explain about the different methods of Scanner Class and their methods.

The most common method of taking an input in a java program is through Scanner Class which is imported from the Java Utility Package by using the statement given below.

import java.util.Scanner; /*imported at beginning of the java program*/

The Input is given with the help input stream System.in

Syntax:

Scanner KB=new Scanner(System.in);
/*Where KB is an object name, you can change it as per your choice*/

There are different input methods provided in Scanner class for different primitive data types such as:

Data TypeMethod
Integer nextInt()
Double nextDouble()
Long nextLong()
Float nextFloat()
Byte NextByte()
String nextLine() /*Allows Spaces between a String */
next() /*Won’t Allow Spaces between a String */

Consider the program:

import java.util.Scanner;

class UnexpectedBehaviour
{
	public static void main(String args[])
	{
		Scanner KB=new Scanner(System.in);
		
		int i;
		float f;
		String s;
		
		i=KB.nextInt();
		f=KB.nextFloat();
		s=KB.nextLine();
		
		System.out.println("Output String is : "+s);
		System.out.println("Output Integer is : "+i);
		System.out.println("Output Float is : "+f);
	}
}

Output

1
8.8
Output String is :
Output Integer is : 1 
Output Float is : 8.8 

But this unexpected behaviour arises when we use nextLine() method right after next method of data types other than String such as nextInt() , nextDouble() , nextFloat() etc. Specific methods read specific tokens and so in the above program right after KB.nextFloat()the new line character will be still in the input buffer and String method takes input of the remaining part of nextFloat() which will be nothing in the above case.

To tackle the given problem we add KB.nextLine() right above s=KB.nextLine();

Consider the program:

import java.util.Scanner;

class UnexpectedBehaviour
{
	public static void main(String args[])
	{
		Scanner KB=new Scanner(System.in);
		
		int i;
		float f;
		String s;
		
		i=KB.nextInt();
		f=KB.nextFloat();
		KB.nextLine();
		s=KB.nextLine();
		
		System.out.println("Output String is : "+s);
		System.out.println("Output Integer is : "+i);
		System.out.println("Output Float is : "+f);
	}
}

Output

1 
8.8 
Java is Cool !
Output String is : Java is Cool ! 
Output Integer is : 1 
Output Float is : 8.8








COMMENTS