Java Scanner nextLine()方法及示例
java.util.Scanner 类的 nextLine() 方法将该扫描器推进到当前行,并返回被跳过的输入。这个函数打印出当前行的其余部分,省去了行尾的分隔符。下一个被设置为行分隔符之后。由于该方法继续在输入中寻找分线符,如果没有分线符,它可能会搜索所有的输入,寻找要跳过的那一行。
语法
public String nextLine()
参数: 该函数不接受任何参数。
返回值: 该方法返回被跳过的那 一行 。
异常: 该函数会抛出两个异常,如下所述。
- NoSuchElementException: 如果没有找到行,则抛出。
- IllegalStateException: 如果该扫描器被关闭,则抛出。
下面的程序说明了上述函数。
程序1 :
// Java program to illustrate the
// nextLine() method of Scanner class in Java
// without parameter
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
String s = "Gfg \n Geeks \n GeeksForGeeks";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
// print the next line
System.out.println(scanner.nextLine());
// print the next line again
System.out.println(scanner.nextLine());
// print the next line again
System.out.println(scanner.nextLine());
scanner.close();
}
}
输出:
Gfg
Geeks
GeeksForGeeks
程序2: 演示NoSuchElementException
// Java program to illustrate the
// nextLine() method of Scanner class in Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
String s = "";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
System.out.println(scanner.nextLine());
scanner.close();
}
catch (Exception e) {
System.out.println("Exception thrown: " + e);
}
}
}
输出:
Exception thrown: java.util.NoSuchElementException: No line found
程序3: 演示IllegalStateException
// Java program to illustrate the
// nextLine() method of Scanner class in Java
// without parameter
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
String s = "Gfg";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
scanner.close();
// Prints the new line
System.out.println(scanner.nextLine());
scanner.close();
}
catch (Exception e) {
System.out.println("Exception thrown: " + e);
}
}
}
输出:
Exception thrown: java.lang.IllegalStateException: Scanner closed
**参考资料: ** https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()