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


Java Scanner close()用法及代碼示例


java.util.Scanner類的close()方法關閉已打開的掃描器。如果掃描儀已經關閉,則在調用此方法時將無效。

用法:

public void close()

返回值:該函數不返回任何值。


以下示例程序旨在說明上述函數:

示例1:

// Java program to illustrate the 
// close() method of Scanner class in Java 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // Get the string 
            String s = "Geeksforgeeks has Scanner Class Methods"; 
  
            // create a new scanner 
            // with the specified String Object 
            Scanner scanner = new Scanner(s); 
  
            // print the next line of the string 
            System.out.println("Scanner: "
                               + scanner.nextLine()); 
  
            // close the scanner 
            scanner.close(); 
  
            System.out.println("\nScanner Closed.\n"); 
  
            System.out.println("Trying to use scanner"
                               + " after closing."); 
  
            // print the next line of the string 
            System.out.println(scanner.nextLine()); 
        } 
  
        catch (Exception e) { 
            System.out.println("Exception thrown:\n" + e); 
        } 
    } 
}
輸出:
Scanner: Geeksforgeeks has Scanner Class Methods

Scanner Closed.

Trying to use scanner after closing.
Exception thrown:
java.lang.IllegalStateException: Scanner closed

參考: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()



相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 Scanner close() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。