본문 바로가기
Java

.split (.)을 분리할 때 (코드업 1019번 java)

by karonano 2023. 3. 15.
728x90
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String date[] = sc.next().split("[.]");    // [.] or \\. 사용
        int year = Integer.parseInt(date[0]);
        int month = Integer.parseInt(date[1]);
        int day = Integer.parseInt(date[2]);
        System.out.print(String.format("%04d", year) + "." + String.format("%02d", month) + "." + String.format("%02d", day));
    }
}

이 문제는 입력받은 연, 월, 일을 yyyy.mm.dd 형식으로 출력한다.
(%02d를 사용하면 2칸을 사용해 출력하는데, 한 자리 수인 경우 앞에 0을 붙여 출력한다.)

 

scanner를 사용하여 입력 받고 String으로 이용해 문자열 타입 = split으로 ("[.]")  '
.'을 기준으로 분리해야 하는 경우 특별하게 [.] 또는 \\.을 이용해서 분리해야한다

 

[코드업 자바] # 1019 [기초-입출력] 연월일 입력받아 그대로 출력하기 — 알음알음 성장로그 (tistory.com)

 

연,월,일을 배열로 선언

  • Integer.parseInt(n) : 문자형 숫자(String 1, 2..)를 정수형으로 변환
  • String.format("%04d", num) : num을 4자리 정수형태로 반환
    • cf. String.format("%.2f", num) : num을 소수 둘째 자리까지 반환