Codeup 예제 1019번 문항의 풀이에서,
특수문자(".")로 나눠져 있는 String에 대하여 (예시 입력값 "2020.8.20"),
2020
8
20
위와 같이 쪼개서 답을 풀어야한다.
하지만 date값으로 받은 2020.8.20은 아래와 같은 코드로는 쪼개지지 않는다.
※ 오답
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String date = sc.nextLine();
int yyyy = Integer.parseInt(date.split(".")[0]); // 첫줄에서 바로 에러가 난다.
int mm = Integer.parseInt(date.split(".")[1]);
int dd = Integer.parseInt(date.split(".")[2]);
System.out.printf("%04d.%02d.%02d\n", yyyy, mm, dd);
}
}
마침표 "."로 나누어진 String을 split 하기 위해서는
[.] 와 같이[ ] 로 감싸주거나
\\. 와 같이 \\를 앞에 입력해 주어야 한다.
※ 정답
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String date = sc.nextLine();
int yyyy = Integer.parseInt(date.split("[.]")[0]);
int mm = Integer.parseInt(date.split("[.]")[1]);
int dd = Integer.parseInt(date.split("[.]")[2]);
System.out.printf("%04d.%02d.%02d\n", yyyy, mm, dd);
}
}
// 입력값 = 2020.8.8
// 결과값 = 2020.08.08
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String date = sc.nextLine();
int yyyy = Integer.parseInt(date.split("\\.")[0]);
int mm = Integer.parseInt(date.split("\\.")[1]);
int dd = Integer.parseInt(date.split("\\.")[2]);
System.out.printf("%04d.%02d.%02d\n", yyyy, mm, dd);
}
}
//입력값 = 2020.8.8
//결과값 = 2020.08.08