當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。