콘솔 클래스는 콘솔(키보드/스크린) 장치에서 데이터를 쓰거나 읽는 데 사용됩니다. readLine()을 제공합니다. 키보드에서 줄을 읽는 방법입니다. console()을 사용하여 콘솔 클래스의 객체를 가져올 수 있습니다. 방법.
참고 − 이 프로그램을 IDE와 같은 비대화형 환경에서 실행하려고 하면 작동하지 않습니다.
예
다음 Java 프로그램은 콘솔을 사용하여 사용자로부터 데이터를 읽습니다. 수업.
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