Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 효율적인연산
- 자바실행방법
- 자바형식
- SQL
- 클래스배열
- 자바자료형
- 자바접근지정자
- 누승재귀
- 자바제어문
- read()함수
- 겟셋함수
- 중첩for문
- 기타제어자
- 자바클래스
- 오버로딩
- 변수명명규칙
- 자바상수
- 자바switch문
- 변수의 초기화
- 프로그래머스
- 연산자우선순위
- 자바기타제어자
- 자바수우미양가
- 자바별찍기
- 자바if문
- 자바함수
- 오라클
- 반복문라벨
- 자바연산자
- 팩토리얼재귀
Archives
- Today
- Total
h-i-s-t-o-r-y
[Java] 형식화 클래스 (~Format) 본문
package days23;
import java.text.DecimalFormat;
public class Ex10 {
public static void main(String[] args) {
// p.540 형식화 클래스
/*
* 1. p.540 DecimalFormat 숫자형 -> 형식클래스
* 2. p.544 SimpleDateFormat 날짜형 -> 형식클래스
* 3. p.548 ChoiceFormat 특정범위 속하는 값 -> 문자열로 변환
* ex. 90<=kor<=100
* 4. p.549 MessageFormat 메시지(문자열) -> 형식클래스
*
*/
double number = 1234567.89;
String[] pattern = {
"0",
"#",
"0.0",
"#.#",
"0000000000.0000",
"##########.####",
"#.#-",
"-#.#",
"#,###.##",
"#,####.##",
"#E0",
"0E0",
"##E0",
"00E0",
"####E0",
"0000E0",
"#.#E0",
"0.0E0",
"0.000000000E0",
"00.00000000E0",
"000.0000000E0",
"#.#########E0",
"##.########E0",
"###.#######E0",
"#,###.##+;#,###.##-",
"#.#%",
"#.#\u2030",
"\u00A4 #,###",
"'#'#,###",
"''#,###",
};
for(int i=0; i < pattern.length; i++) {
DecimalFormat df = new DecimalFormat(pattern[i]);
System.out.printf("%19s : %s\n",pattern[i], df.format(number));
}
}//main
}//class
package days23;
import java.text.DecimalFormat;
import java.text.ParseException;
public class Ex11 {
public static void main(String[] args) throws ParseException {
// p.543 DecimalFormat 클래스의 parse() , format() 이해
String s = "1,234,567.89";
//"#,###.##" -> "#.#####E0"
//
DecimalFormat df = new DecimalFormat("#,###.##");
// Integer.parseInt()는 콤마(,)있는 문자열 변환 못함
// df.parse() String -> Number 숫자로 변환
Number n = df.parse(s);
double d = n.doubleValue(); //더블타입
System.out.println(d); //1234567.89
//
DecimalFormat df2 = new DecimalFormat("#.#####E0");
// df.format() 숫자를 형식을 적용한 문자로 변환
System.out.println(df2.format(d)); //1.23457E6
System.out.println();
/*
double d1 = Double.parseDouble(s.replace(",", ""));
System.out.println(d1); //1234567.89
// double 1234567.89
// double 1.235E6
String e = String.format("%E", d1);
System.out.println(e); //1.234568E+06
*/
}//main
}//class
package days24;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Ex01 {
public static void main(String[] args) {
// p.544 *** SimepleDateFormat 클래스 ***
// Date, Calendar -> 형식으로 날짜/시간 정보 출력
// 표 10-2 패턴에 사용되는 기호
/*
Date d = new Date();
//2021-04-08
String pattern = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String result = sdf.format(d); //패턴적용
System.out.println(result);
*/
Calendar c = Calendar.getInstance();
String pattern = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String result = sdf.format(c.getTime());
System.out.println(result);
}
}
package days24;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Ex02 {
public static void main(String[] args) {
// p.545 예제 10-12
Date today = new Date();
SimpleDateFormat sdf1, sdf2, sdf3, sdf4;
SimpleDateFormat sdf5, sdf6, sdf7, sdf8, sdf9;
sdf1 = new SimpleDateFormat("yyyy-MM-dd");
sdf2 = new SimpleDateFormat("''yy년 MMM dd일 E요일");
sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf4 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
sdf5 = new SimpleDateFormat("오늘은 올 해의 D번째 날입니다.");
sdf6 = new SimpleDateFormat("오늘은 이 달의 d번째 날입니다.");
sdf7 = new SimpleDateFormat("오늘은 올 해의 w번째 주입니다.");
sdf8 = new SimpleDateFormat("오늘은 이 달의 W번째 날입니다.");
sdf9 = new SimpleDateFormat("오늘은 이 달의 F번째 E요일입니다.");
System.out.println(sdf1.format(today)); // format(Date d)
System.out.println(sdf2.format(today));
System.out.println(sdf3.format(today));
System.out.println(sdf4.format(today));
System.out.println();
System.out.println(sdf5.format(today));
System.out.println(sdf6.format(today));
System.out.println(sdf7.format(today));
System.out.println(sdf8.format(today));
System.out.println(sdf9.format(today));
}
}
package days24;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Ex03 {
public static void main(String[] args) throws ParseException {
// 문제) 문자열 "2015년 11월 23일" -> 문자열 "2015/11/23" 변환
String source = "2015년 11월 23일";
//Date 변환 sdf.parse()
// sdf2.format()
//String "2015/11/23"
// 풀이1) 정규표현식
//source = source.replaceAll("([가-힣]|\\s)", "/");
// 한글도 /로, 공백도 /로 바꿔버림 2015//11//23
// source = source.replaceAll("[가-힣]", "").replaceAll("\\s", "/");
// System.out.println(source);
// 풀이2) sdf
SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 mm월 dd일");
Date d = sdf.parse(source);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/mm/dd");
source = sdf2.format(d);
System.out.println(source);
}
}
package days24;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Scanner;
public class Ex04 {
public static void main(String[] args) {
// "2021/04/08" -> Date 날짜 객체로 변환시켜서 출력.
// 날짜를 입력받는데 위의 패턴으로 입력하면 출력-종료
// X 다시 입력 반복
String pattern = "yyyy/MM/dd";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date inputDate = null;
String source = null;
try (Scanner scanner = new Scanner(System.in);) {
do {
System.out.print("> 날짜 입력 (예:2021/04/08) ? ");
source = scanner.nextLine();
try {
inputDate = sdf.parse(source);
} catch (ParseException e) {
System.out.println(" 날짜 입력 형식 XXX \n>다시 ");
}
} while (Objects.isNull(inputDate));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(inputDate.toLocaleString());
}//main
}//class
package days24;
import java.util.Date;
import java.util.Objects;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Ex04_02 {
public static void main(String[] args) {
// "2021/04/08" -> Date 날짜 객체로 변환시켜서 출력.
// 날짜를 입력받는데 위의 패턴으로 입력하면 출력-종료
// X 다시 입력 반복
String input = null;
String regex = "(\\d{4})/(\\d{1,2})/(\\d{1,2})";
Pattern p = Pattern.compile(regex);
Matcher m = null;
Scanner scanner = new Scanner(System.in);
Date d = null;
do {
System.out.print("> 날짜 입력 (예:2019/12/23) ? ");
input = scanner.nextLine();
m = p.matcher(input);
if (m.matches()) {
// year month day
d = new Date(Integer.parseInt(m.group(1))-1900
, Integer.parseInt(m.group(2))-1
, Integer.parseInt(m.group(3)));
}
} while (Objects.isNull(d));
//출력
System.out.println(d.toLocaleString());
}//main
}//class
package days24;
import java.text.ChoiceFormat;
public class Ex05 {
public static void main(String[] args) {
// p.548 ChoiceFormat
// 특정 범위에 속하는 값을 문자열로 변환해준다
// 예) 90 <= kor <= 100 "수우미양가"
// 1번 방식
// 왜 double 배열 이냐면 ..
double[] limits = {50, 60, 70, 80, 90};
String[] grades = {"가", "양", "미", "우", "수"};
// 매개변수 double배열, String배열
ChoiceFormat cf = new ChoiceFormat(limits, grades);
// 2번 방식
String newPattern = "50#가|60#양|70#미|80#우|90#수";
ChoiceFormat cf2 = new ChoiceFormat(newPattern);
int[] scores = {100, 95, 88, 70, 52, 60, 70};
for (int i = 0; i < scores.length; i++) {
System.out.printf("%d : %s\n"
, scores[i]
, cf.format(scores[i]));
}
}
}
package days24;
import java.text.MessageFormat;
public class Ex06 {
public static void main(String[] args) {
// p.549 MessageFormat 클래스
// 데이터를 정해진 형식에 맞게 출력하는 클래스
String name = "홍길동";
int age = 20;
char grade = 'A';
boolean gender = true;
double avg = 89.23;
// 출력형식 지정 (3가지)
// 1
System.out.printf("이름:%s, 나이:%d, 등급:%c, 성별:%b, 평균:%.2f\n"
, name, age, grade, gender, avg);
// 2. String String.format()
String result = String.format("이름:%s, 나이:%d, 등급:%c, 성별:%b, 평균:%.2f\n"
, name, age, grade, gender, avg);
System.out.println( result );
// 3. String MessageFormat 클래스
String pattern = "이름:{0}, 나이:{1}, 등급:{2}, 성별:{3}, 평균:{4}";
result = MessageFormat.format(pattern, name, age, grade, gender, avg);
System.out.println( result );
// 예제 10-18
// 왜 MessageFormat 쓰나 ?
// printf의 %출력서식 이랑 다르게 {순번}만 주면 알아서 들어감
// 편한걸로 쓰면 됨
String msg = "Name: {0}\nTel: {1}\nAge: {2}\nbirthday: {3}";
Object[] arguments = {"이자바", "02-123-1234", "27", "07-09"};
// msg 형식으로 arguments 요소를 출력
String result = MessageFormat.format(msg, arguments);
System.out.println(result);
}
}
> p.550, 551 예제 10-20, 10-21
package days24;
import java.text.MessageFormat;
import java.text.ParseException;
public class Ex07 {
public static void main(String[] args) throws ParseException {
// MessageFormatEx2
String tableName = "CUST_INFO";
String msg = "INSERT INTO " + tableName
+ " VALUES(''{0}'',''{1}'',''{2}'',''{3}'');";
Object[][] arguments = {
{"임희원","02-123-1234","27","07-09"},
{"도토리","032-333-1234","33","10-07"},
};
for (int i = 0; i < arguments.length; i++) {
String result = MessageFormat.format(msg, arguments[i]);
System.out.println(result);
}
/* 결과
INSERT INTO CUST_INFO VALUES('임희원','02-123-1234','27','07-09');
INSERT INTO CUST_INFO VALUES('도토리','032-333-1234','33','10-07');
*/
// MessageFormatEx3
String[] data = {
"INSERT INTO CUST_INFO VALUES ('임희원','02-123-1234',27,'07-09');",
"INSERT INTO CUST_INFO VALUES ('도토리','032-333-1234',33,'10-07');"
};
String pattern = "INSERT INTO CUST_INFO VALUES ({0},{1},{2},{3});";
MessageFormat mf = new MessageFormat(pattern);
for (int i = 0; i < data.length; i++) {
Object[] objs = mf.parse(data[i]);
for (int j = 0; j < objs.length; j++) {
System.out.println(objs[j]+",");
}
System.out.println();
}
/* 결과
'임희원',
'02-123-1234',
27,
'07-09',
'도토리',
'032-333-1234',
33,
'10-07',
*/
}
}
'Java' 카테고리의 다른 글
[Java] Date, Calendar 클래스 (java.util 패키지) (0) | 2021.07.17 |
---|---|
[Java] String 클래스 - 문자열 관련 메서드들 정리 (0) | 2021.07.17 |
[Java] 예외 처리 (Exception Handling) (0) | 2021.07.17 |
[Java] 추상화 / 인터페이스(Interface) / 익명 클래스(anonomous class) (0) | 2021.07.17 |
[Java] 클래스의 특징 - 다형성 / UpCasting, DownCasting (0) | 2021.07.17 |