Java.io.Console.readLine() 方法



描述

java.io.Console.reader() 方法從控制檯讀取一行文字。

宣告

以下是java.io.Console.readLine() 方法的宣告:

public String readLine()

引數

返回值

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

異常

IOError − 如果發生 I/O 錯誤。

示例

以下示例演示了 java.io.Console.readLine() 方法的用法。

package com.tutorialspoint;

import java.io.Console;

public class ConsoleDemo {
   public static void main(String[] args) {      
      Console cnsl = null;
      String name = null;
      
      try {
         // creates a console object
         cnsl = System.console();

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

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

Name: Master Programmer
Name entered : Master Programmer
java_io_console.htm
廣告