Scanner hasNextLine() method in Java with Examples
Last Updated :
16 Oct, 2018
The hasNextLine() method of java.util.Scanner class returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.
Syntax:
public boolean hasNextLine()
Parameters: The function does not accepts any parameter.
Return Value: This function returns true if and only if this scanner has another line of input
Exceptions: The function throws IllegalStateException if this scanner is closed.
Below programs illustrate the above function:
Program 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
String s = "gfg 2 geeks!" ;
Scanner scanner = new Scanner(s);
scanner.useLocale(Locale.US);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}
|
Program 2: Program to demonstrate exception
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
String s = "gfg 2 geeks!" ;
Scanner scanner = new Scanner(s);
scanner.useLocale(Locale.US);
scanner.close();
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
catch (IllegalStateException e) {
System.out.println( "Exception is: " + e);
}
}
}
|
Output:
Exception is: java.lang.IllegalStateException: Scanner closed
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine()
Share your thoughts in the comments
Please Login to comment...