[Java]자바에서 입출력하기 (Scanner)

Dev-Whale·2023년 5월 29일
0
post-thumbnail

코딩테스트를 위한 자바 입출력 방식 정리

자바에서의 입력

자바에서 입력은 보통 Scanner와 Bufferdreader를 주로 사용한다
받는 입력의 형식에 따라 받아서 처리하는 방식이 다른데 자세한건 아래에서 코드를 보면서 다뤄볼려고 한다

Scanner를 사용하는 방법

Scanner 특징

  • 스캐너는 공백(띄어쓰기) 또는 개행(줄 바꿈), 탭을 기준으로 읽는다.
  • 기본적인 데이터 타입을 모두 입력받을 수 있다.

Scanner 클래스 사용법

  • 먼저 util 패키지를 경로의 Scanner 클래스를 임포트 해주어야한다.
// 두가지 방법중에 선택해서 사용한다.
import java.util.Scanner; // java.util안의 Scanner 클래스 impor
import java.util.*; // java.util에 있는 모든 클래스 import
  • Scanner 객체 생성, 객체이름은 본인이 원하는대로 작성하고 Scanner생성자에 매개변수로 System.in을 담아서 객체를 생성해준다.
// System.in은 입력한 값을 Byte 단위로 읽어주는 자바의 표준 입력 스트림
Scanner sc = new Scanner(System.in); // Scanner 객체 생성
  • Scanner 클래스의 메서드들을 통해 입력받기
    - next() : String 읽기 Token을 기준으로 읽음
    - nextLine() : String 읽기. Enter를 기준으로 읽음
    - nextInt() : int를 읽음
    - nextBoolean() : boolean을 읽음
    - nextByte() : byte를 읽음
    - nextShort() : short 를 읽음
    - nextLong() : long 을 읽음
    - nextFloat() : float 을 읽음
    - nextDouble() : double 을 읽음

EX)

Scanner sc = new Scanner(System.in);
String scNext =  sc.next();					// input : hello world, scNext  : hello
String scNextLine = sc.nextLine(); 			// input : hello world, scNextLine : hello world
int scNextInt = sc.nextInt() ;				// input : 1, scNextInt 1
boolean  scNextBoolean = sc.nextBoolean(); 	// input : true, scNextBoolean : true				
byte scNextByte = sc.nextByte() ;			// input : 1, scNextByte : 1
short scNextShort = sc.nextShort();			// input : 1, scNextShort : 1
long scNextLong = sc.nextLong() ;			// input : 1, scNextLong : 1
float scNextFloat = sc.nextFloat();			// input : 1, scNextFloat : 1.0
double scNextDouble = sc.nextDouble();		// input : 1, scNextDouble : 1.0
profile
개발하는 고래

0개의 댓글