> Java > java지도 시간 > 본문

Java 사용자 입력

WBOY
풀어 주다: 2024-08-30 16:06:42
원래의
436명이 탐색했습니다.

Java 프로그램에는 명령줄 환경에서 사용자 입력을 읽어서 사용자 입력을 얻을 수 있는 방법이 3가지 있는데, Java BufferedReader 클래스, Java Scanner 클래스, Console 클래스입니다. 수업에 대해 자세히 알아보겠습니다. 사용자 입력을 얻기 위해 Scanner 클래스를 사용합니다. 이 프로그램은 사용자에게 정수, 문자열, 부동소수점을 입력하도록 요청하고 이를 디스플레이에 인쇄합니다. java.util의 스캐너 클래스가 존재하므로 이 패키지를 소프트웨어에 추가할 수 있습니다. 먼저 Scanner Class 객체를 생성하고 Scanner Class 메소드를 사용합니다.

Java 사용자 입력의 3가지 방법

사용자 입력을 읽는 세 가지 방법이 있습니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

  1. Java BufferedReader 클래스
  2. 자바 스캐너 수업
  3. 콘솔 클래스 사용

이 세 클래스는 아래에 언급되어 있습니다. 자세히 논의해 보겠습니다.

1. Java BufferedReader 클래스

독자 클래스를 확장합니다. BufferedReader는 문자 입력 스트림에서 입력을 읽고 모든 입력을 효율적으로 읽을 수 있도록 문자를 버퍼링합니다. 버퍼링을 위한 기본 크기는 큽니다. 사용자가 읽기를 요청하면 해당 요청이 리더기로 이동하고 문자 또는 바이트 스트림에 대한 읽기 요청이 이루어집니다. 따라서 BufferedReader 클래스는 FileReader 또는 InputStreamReaders와 같은 다른 입력 스트림 주위에 래핑됩니다.

예:

BufferedReader reader = new BufferedReader(new FileReader("foo.in"));
로그인 후 복사

BufferedReader는 readLine() 메서드를 사용하여 한 줄씩 데이터를 읽을 수 있습니다.

BufferedReader를 사용하면 코드 성능이 더 빨라질 수 있습니다.

건축자

BufferedReader에는 다음과 같은 두 개의 생성자가 있습니다.

1. BufferedReader(리더 리더): 입력 버퍼의 기본 크기를 사용하는 버퍼링된 입력 문자 스트림을 생성하는 데 사용됩니다.

2. BufferedReader(리더 리더, 입력 크기): 입력 버퍼에 제공된 크기를 사용하는 버퍼링된 입력 문자 스트림을 생성하는 데 사용됩니다.

기능
  • int read: 단일 문자를 읽는 데 사용됩니다.
  • int read(char[] cbuffer,  int offset,  int length):  배열의 지정된 부분에 있는 문자를 읽는 데 사용됩니다.
  • String readLine ():  입력을 한 줄씩 읽는 데 사용됩니다.
  • boolean Ready():  입력 버퍼를 읽을 준비가 되었는지 테스트하는 데 사용됩니다.
  • 긴 건너뛰기: 문자를 건너뛰는 데 사용됩니다.
  • void close(): 입력 스트림 버퍼와 스트림과 관련된 시스템 리소스를 닫습니다.

사용자가 키보드에서 문자를 입력하면 장치 버퍼에서 읽은 다음 System.in에서 버퍼 리더 또는 입력 스트림 리더로 전달되어 입력 버퍼에 저장됩니다.

코드:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*package whatever //do not write package name here */
class BufferedReaderDemo {
public static void main (String[] args) throws NumberFormatException, IOException {
System.out.println("Enter your number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
System.out.println("Number you entered is: " + t);
System.out.println("Enter your string");
String s  = br.readLine();
System.out.println("String you entered is: " + s);
}
}
로그인 후 복사

출력:

Java 사용자 입력

InputStreamReader 및 BufferedReader에서 읽는 프로그램:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderDemo {
public static void main(String args[]) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(reader);
System.out.println("What is your name?");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
로그인 후 복사

출력:

Java 사용자 입력

2. 자바 스캐너 클래스

java.util. scanner 클래스는 키보드에서 사용자 입력을 읽는 데 사용되는 클래스 중 하나입니다. util 패키지에서 사용할 수 있습니다. 스캐너 클래스는 기본적으로 대부분 공백인 구분 기호를 사용하여 사용자 입력을 구분합니다. 스캐너에는 double, int, float, long, Boolean, short, byte 등과 같은 다양한 기본 유형의 콘솔 입력을 읽는 여러 가지 방법이 있습니다. 이는 Java에서 입력을 얻는 가장 간단한 방법입니다. Scanner 클래스는 Iterator 및 Closeable 인터페이스를 구현합니다. 스캐너는 기본 유형의 입력을 읽기 위한 nextInt() 및 다양한 기본 유형 메소드를 제공합니다. 문자열 입력에는 next() 메소드가 사용됩니다.

Constructors
  • Scanner(File source): It constructs a scanner to read from a specified file.
  • Scanner(File source, String charsetName):  It constructs a scanner to read from a specified file.
  • Scanner(InputStream source), Scanner(InputStream source, String charsetName): It constructs a scanner to read from a specified input stream.
  • Scanner(0Readable source):  It constructs a scanner to read from a specified readable source.
  • Scanner(String source):  It constructs a scanner to read from a specified string source.
  • Scanner(ReadableByteChannel source): It constructs a scanner to read from a specified channel source.
  • Scanner(ReadableByteChannel source, String charsetName): It constructs a scanner to read from a specified channel source.
Functions

Below are mentioned the method to scan the primitive types from console input through Scanner class.

  • nextInt(),
  • nextFloat(),
  • nectDouble(),
  • nextLong(),
  • nextShort(),
  • nextBoolean(),
  • nextDouble(),
  • nextByte(),

Program to read from Scanner Class:

Using scanner class.
import java.util.Scanner;
/*package whatever //do not write package name here */
class ScannerDemo {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your number");
int t = sc.nextInt();
System.out.println("Number you entered is: " + t);
System.out.println("Enter your string");
String s  = sc.next();
System.out.println("String you entered is: " + s);
}
}
로그인 후 복사

Output:

Java 사용자 입력

3. Using console Class

Using the console class to read the input from the command-line interface. It does not work on IDE.

Code:

public class Main
{
public static void main(String[] args)
{
// Using Console to input data from user
System.out.println("Enter your data");
String name = System.console().readLine();
System.out.println("You entered: "+name);
}
}
로그인 후 복사

Output:

Java 사용자 입력

위 내용은 Java 사용자 입력의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!