Java Scanner hasNextLine() 方法



描述

Java Scanner hasNextLine() 方法返回 true,如果此掃描器的輸入中還有另一行。此方法在等待輸入時可能會阻塞。掃描器不會越過任何輸入。

宣告

以下是 java.util.Scanner.hasNextLine() 方法的宣告

public boolean hasNextLine()

引數

返回值

當且僅當此掃描器有另一行輸入時,此方法返回 true

異常

IllegalStateException − 如果此掃描器已關閉

使用字串示例檢查掃描器中是否存在下一行

以下示例演示了 Java Scanner hasNextLine() 方法的使用,用於檢查是否存在下一行。我們使用給定的字串建立了一個掃描器物件。然後我們列印一行,然後使用 hasNextLine() 檢查是否存在更多資料。一旦行結束,hasNextLine() 返回 false。最後,使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) {

      String s = "Hello World! \n 3 + 3.0 = 6 ";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // print the next line
      System.out.println(scanner.nextLine());

      // check if there is a next line again
      System.out.println(scanner.hasNextLine());

      // print the next line
      System.out.println(scanner.nextLine());

      // check if there is a next line again
      System.out.println(scanner.hasNextLine());

      // close the scanner
      scanner.close();
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Hello World! 
true
 3 + 3.0 = 6 
false

使用使用者輸入示例檢查掃描器中是否存在下一行

以下示例演示了 Java Scanner hasNextLine() 方法的使用,用於檢查是否存在下一行。我們使用 System.in 建立了一個掃描器物件。然後我們列印一行,然後使用 hasNextLine() 檢查是否存在更多資料。一旦行結束,hasNextLine() 返回 false。最後,使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) {

      // create a new scanner with the System Input
      Scanner scanner = new Scanner(System.in);

      // print the next line
      System.out.println(scanner.nextLine());

      // check if there is a next line again
      System.out.println(scanner.hasNextLine());

      // close the scanner
      scanner.close();
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:(我們在其中輸入 Hello World 並按 Enter 鍵,然後輸入 Bye 並按 Enter 鍵。)

Hello World
Hello World
Bye
true

使用屬性檔案示例檢查掃描器中是否存在下一行

以下示例演示了 Java Scanner hasNextLine() 方法的使用,用於檢查是否存在下一行。我們使用檔案 properties.txt 建立了一個掃描器物件。然後我們使用 hasNextLine() 方法檢查每一行並列印。最後,使用 close() 方法關閉掃描器。

package com.tutorialspoint;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerDemo {
   public static void main(String[] args) throws FileNotFoundException {

      // create a new scanner with a file as input
      Scanner scanner = new Scanner(new File("properties.txt"));

      // print the next line
      System.out.println(scanner.nextLine());

      // check if there is a next line again
      System.out.println(scanner.hasNextLine());

      // close the scanner
      scanner.close();
   }
}

假設我們在你的 CLASSPATH 中有一個名為 properties.txt 的檔案,其內容如下。此檔案將用作我們示例程式的輸入:

Hello World! 3 + 3.0 = 6

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Hello World! 3 + 3.0 = 6
false
java_util_scanner.htm
廣告
© . All rights reserved.