Java/Java 기본기
[자바의 정석] ChoiceFormat
Serina_Heo
2022. 2. 20. 13:01
특정 범위에 속하는 값을 문자열로 변환하기 위해 ChoiceFormat을 사용할 수 있다. 연속적이나 불연속 적인 범위의 값들을 처리하는데 if 문이나 switch문으로 처리하기에 적절치 못할 때 사용하면 좋다.
생각보다 편하게 처리할 수 있기에 기록해두면 도움 될 것 같아서 자바의 정석 예제 코드를 올려본다.
import java.text.ChoiceFormat;
public class ChoiceFormatEx1 {
public static void main(String[] args) {
double[] limits = {60, 70, 80, 90};
// limit은 오름차순으로 써야한다. ChoiceFormat의 생성자에 그렇게 정의되어있다.
String[] grades = {"D", "C", "B", "A"};
int[] scores = {100, 95, 88, 70, 52, 60, 70};
ChoiceFormat form = new ChoiceFormat(limits, grades);
for(int i=0; i<scores.length; i++) {
System.out.println(scores[i] + " : "+ form.format(scores[i]));
}
}
}
아래 코드의 pattern에 보면 구분자로 #와 < 두 가지가 있는데
- #: 경계값 포함 (아래 코드에서 90은 A가 됨)
- <: 경계값 미포함 (아래 코드에서 80은 C가 됨)
import java.text.ChoiceFormat;
public class ChoiceFormatEx2 {
public static void main(String[] args) {
String pattern = "60#D|70#C|80<B|90#A";
int[] scores = {91, 90, 80, 88, 70, 52, 60};
ChoiceFormat form = new ChoiceFormat(pattern);
for(int i=0; i < scores.length; i++) {
System.out.println(scores[i] + " : " + form.format(scores[i]));
}
}
}
예제코드 ref: 자바의 정석 3판 예제 10-16, 10-17