https://www.acmicpc.net/problem/4358
이 문제는 총 입력개수를 미리 알려 주지 않는다
따라서 데이터를 읽고 끝내는 처리를 해야하는데 인터넷으로 찾아보고 시도해봤지만 다음입력까지 계속 대기하기만 하는 현상이 발생한다. 처음에는 Intellij 오류인줄 알고 이거 때문에 3~4시간을 날렸다.
알고보니 다음 입력을 기다리는 것이었다. 구글릴을 해봐도 뾰족한 수는 없었다
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String tree = "";
while((tree = br.readLine()) != null)
{
}
br.readLine(); 이 부분에서 입력하기 전까지 그냥 대기 하고 진행이 되질 않는다 그래서 입력데이터 끝에 그냥 "exit" 를 넣었다
그리고 eixt 읽으면 break 타게 수정해서 디버깅 할 수 있었다
while(true)
{
tree = br.readLine();
if(tree == null || tree.equals("exit"))
break;
}
그리고 이문제는 결과 출력할때도 조심해야한다. 나무의 이름과 퍼센테이지 찍을때
String.format 을 사용한다면 다음과 같이 분리해서 찍어야 한다
나무이름 + String.format("%.4f", ~~~~ )
다음처럼 찍으면 String.format 에서 Exception 오류 난다 나무 이름 문자열중에 "%" 문자가 들어가 있는게 있어서 그런다고 한다. 정말 황당하다;;
String.format(나무이름 + "%.4f", ~~~~ )
다 풀고 나서도 좀 짜증이 났다. 알고리즘에만 집중해서 풀고 싶은데 이런 부분들 때문에 시간을 날린거 같아서.
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
TreeMap<String, Integer> map = new TreeMap<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String tree = "";
int total = 0;
while(true) {
tree = br.readLine();
if(tree == null || tree.equals("exit"))
break;
if(map.containsKey(tree))
{
map.put(tree.toString(), map.get(tree)+1);
}
else
{
map.put(tree.toString(), 1);
}
total++;
}
StringBuilder sb = new StringBuilder();
for(String key : map.keySet())
{
sb.append(key + " " + String.format("%.4f", 100f * (float)map.get(key)/(float)total) + "\n");
}
System.out.println(sb.toString());
}
}
Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow
exit