문제
입력 받은 대로 출력하는 프로그램을 작성하시오.
입력
입력이 주어진다. 입력은 최대 100줄로 이루어져 있고, 알파벳 소문자, 대문자, 공백, 숫자로만 이루어져 있다. 각 줄은 100글자를 넘지 않으며, 빈 줄은 주어지지 않는다. 또, 각 줄은 공백으로 시작하지 않고, 공백으로 끝나지 않는다.
출력
입력받은 그대로 출력한다.
제출 답안1 - 오답, 틀린이유
- 답을 제출하니 틀렸다는 결과가 발생했는데 왜인지 감이 잘 안와서 챗 gpt에 질문했다.
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main{
public static void main(String[] args){
for(int i=0; i<100; i++){
Scanner sc = new Scanner(System.in);
String pattern = "^(?!\\s)(?!.*\\s$)[a-zA-Z0-9\\s]*$";
Pattern inputPattern = Pattern.compile(pattern);
while(sc.hasNextLine()){
String input = sc.nextLine();
Matcher matcher = inputPattern.matcher(input);
if(matcher.matches()){
System.out.println(input);
break;
}
}
sc.close();
}
}
}
- 100번을 반복한다는 조건인 루프를 돌면서 매번 새로 생성하도록 만든 Scanner 클래스의 위치가 문제인듯 보였다.
- 상단에 스캐너 클래스를 하나 생성하여 여러줄을 입력받을 수 있도록 수정하였다.
제출답안 : 수정답안, 정답
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String pattern = "^(?!\\s)(?!.*\\s$)[a-zA-Z0-9\\s]*$";
Pattern inputPattern = Pattern.compile(pattern);
for (int i = 0; i < 100; i++) {
if (sc.hasNextLine()) {
String input = sc.nextLine();
Matcher matcher = inputPattern.matcher(input);
if (matcher.matches()) {
System.out.println(input);
}
}
}
sc.close();
}
}
'문제 풀이 > 알고리즘 풀이' 카테고리의 다른 글
[백준/3003번/JAVA] 킹, 퀸, 룩, 비숍, 나이트, 폰 (1) | 2023.10.16 |
---|---|
[백준/25083번/JAVA] 새싹 (0) | 2023.10.16 |
[백준/5622번/JAVA] 다이얼 (0) | 2023.09.13 |
[백준/2908번/JAVA] 상수 (0) | 2023.09.06 |
[백준/1152번/JAVA] 단어의 개수 (0) | 2023.09.06 |