Java.io.Console.readLine() 方法



描述

java.io.Console.readLine(String fmt, Object... args) 方法提供格式化的提示,然後從控制檯讀取一行文字。

宣告

以下是 java.io.Console.readLine(String fmt, Object... args) 方法的宣告:

public String readLine(String fmt, Object... args)

引數

  • fmt

  • args

返回值

此方法返回包含從控制檯讀取的行(不包括任何行終止字元)的字串,如果已到達流的末尾則返回 null。

異常

  • IllegalFormatException - 如果格式字串包含非法語法、與給定引數不相容的格式說明符、給定格式字串的引數不足或其他非法條件。

  • IOError - 如果發生 I/O 錯誤。

示例

以下示例演示了 java.io.Console.readLine(String fmt, Object... args) 方法的使用。

package com.tutorialspoint;

import java.io.Console;

public class ConsoleDemo {
   public static void main(String[] args) {      
      Console cnsl = null;
      String fmt = "%1$4s %2$5s %3$10s%n";
      String alpha = null;
      
      try {
         // creates a console object
         cnsl = System.console();

         // if console is not null
         if (cnsl != null) {
            
            // read line from the user input
            alpha = cnsl.readLine(fmt, "Enter","Alphabets: ");
            
            // prints
            System.out.println("Alphabets entered: " + alpha);
         }   
         
      } catch(Exception ex) {
         // if any error occurs
         ex.printStackTrace();      
      }
   }
}

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

Enter Alphabets: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Alphabets entered : ABCDEFGHIJKLMNOPQRSTUVWXYZ
java_io_console.htm
廣告