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
广告

© . All rights reserved.