在 Java 中使用 Console 類從鍵盤讀取資料


Console 類用於向控制檯(鍵盤/螢幕)裝置寫入/讀取資料。它提供了一個 readLine() 方法,用於從鍵盤讀取一行。你可以使用 console() 方法獲取 Console 類的物件。

注意 − 如果嘗試在非互動式環境(如 IDE)中執行此程式,則該程式無法工作。

示例

以下 Java 程式使用 Console 類從使用者讀取資料。

 即時演示

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
class Student {
   String name;
   int age;
   float percent;
   boolean isLocal;
   char grade;
   Student(String name, int age, float percent, boolean isLocal, char grade) {
      this.name = name;
      this.age = age;
      this.percent = percent;
      this.isLocal = isLocal;
      this.grade = grade;
   }
   public void displayDetails() {
      System.out.println("Details..............");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Percent: "+this.percent);
      if(this.isLocal) {
         System.out.println("Nationality: Indian");
      }else {
         System.out.println("Nationality: Foreigner");
      }
      System.out.println("Grade: "+this.grade);
   }
}
public class ReadData {
   public static void main(String args[]) throws IOException {
      Console console = System.console();
      if (console == null) {
         System.out.println("Console is not supported");
         System.exit(1);
      }
      System.out.println("Enter your name: ");
      String name = console.readLine();
      System.out.println("Enter your age: ");
      int age = Integer.parseInt(console.readLine());
      System.out.println("Enter your percent: ");
      float percent = Float.parseFloat(console.readLine());
      System.out.println("Are you local (enter true or false): ");
      boolean isLocal = Boolean.parseBoolean(console.readLine());
      System.out.println("Enter your grade(enter A, or, B or, C or, D): ");
      char grade = console.readLine().toCharArray()[0];
      Student std = new Student(name, age, percent, isLocal, grade);
      std.displayDetails();
   }
}

輸出

Enter your name:
Krishna
Enter your age:
26
Enter your percent:
86
Are you local (enter true or false):
true
Enter your grade(enter A, or, B or, C or, D):
A
Details..............
Name: Krishna
Age: 26
Percent: 86.0
Nationality: Indian
Grade: A

更新時間:15-Oct-2019

581 次瀏覽

開啟你的 事業

完成課程獲得認證

開始
廣告