当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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()



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 Scanner nextLine() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。