📜  Java中的 Scanner nextLine() 方法及示例

📅  最后修改于: 2022-05-13 01:55:09.977000             🧑  作者: Mango

Java中的 Scanner nextLine() 方法及示例

Java.util.Scanner类的nextLine()方法将此扫描器前进到当前行并返回被跳过的输入。此函数打印当前行的其余部分,在末尾省略行分隔符。下一个设置在行分隔符之后。由于此方法继续搜索输入以查找行分隔符,因此如果不存在行分隔符,它可能会搜索所有输入以查找要跳过的行。

句法:

public String nextLine()

参数:该函数不接受任何参数。

返回值:此方法返回被跳过的

异常:该函数抛出两个异常,如下所述:

  • NoSuchElementException:如果没有找到行则抛出
  • 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
    {
  
        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: Java/util/Scanner.html#nextLine()