다연이네

[days20] 형식화(format) 클래스 본문

Java

[days20] 형식화(format) 클래스

 다연  2020. 10. 18. 19:31
반응형

1. DecimalFormat      숫자를 원하는 형식으로 출력할 때 사용 ***

2. SimpleDateFormat 날짜를 원하는 형식으로 출력할 때 사용 *****

3. ChoiceFormat       특정 범위에 속하는 값을 문자열로 반환

4. MessageFormat     메시지(문자열)을 원하는 형식으로 출력할 때 사용

 

1. DecimalFormat

	int money = 232000;
	String pattern ="\u00A4#,###"; // \u00A4:₩출력, #,###:천자리마다 ,
	DecimalFormat df = new DecimalFormat(pattern);
	System.out.println(df.format(money)); //₩232,000

2. SimpleDateFormat

Date d = new Date();
		pattern = "yyyy-MM-dd a kk'h':mm'm':ss.SSSS's' E"; 
		//a:오전오후, kk:24시간 기준, E:요일
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		System.out.println(sdf.format(d));
		//2020-10-18 오후 19h:10m:28.0801s 일
		
		Calendar c = Calendar.getInstance();
		pattern ="yyyy-MM-dd(E)";
		SimpleDateFormat sdf2 = new SimpleDateFormat(pattern);
		//sdf -> 캘린더를 받는 객체가 없다
		

* Calendar <-> Date 형변환

		//Calendar -> Date 형변환 
		Calendar c2 = Calendar.getInstance();
		Date d2 = c2.getTime();
		System.out.println(sdf2.format(d2));
		//2020-10-18(일)
		
		//Date -> Calendar 형변환
		Date d3 = new Date();
		Calendar c3 = Calendar.getInstance();
		c3.setTime(d3);

날짜 입력받아 출력하기 

		String pattern = "yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try(Scanner scanner = new Scanner(System.in)) {
			System.out.print("날짜 입력 (ex. 2020-01-01) ");
			String input = scanner.next();
			Date dd = sdf.parse(input);
			System.out.println(dd.toLocaleString());
			
			Calendar cc = Calendar.getInstance();
			cc.setTime(dd);
			System.out.println(cc.getTime().toLocaleString());
		} catch (Exception e) {
			e.printStackTrace();
		}

3. ChoiceFormat

	//1
    int [] scores ={100, 95,88, 73, 52, 60, 70 ,0, 80, 81};
	String pattern = "60#D|70#C|80<B|90#A";
	//#은 경계값을 범위에 포함시키고 <는 포함시키지 않음
	ChoiceFormat cf = new ChoiceFormat(pattern);
	for (int i = 0; i < scores.length; i++) {
		System.out.println(scores[i] + " : " + cf.format(scores[i]));
    }
    
    
    //2
    double [] limits = {0,60, 70, 80, 90}; //asc 오름차순 초이스포맷 매개변수가 더블이라 더블로
		String [] grades = {"가","양","미","우","수"};
		ChoiceFormat cf2 = new ChoiceFormat(limits, grades) ;
		for (int i = 0; i < scores.length; i++) {
			System.out.println(scores[i] + " : " + cf2.format(scores[i]));
		}

4. MessageFormat 

package review;

import java.text.MessageFormat;

public class Review02 {

	public static void main(String[] args) {

		String name ="dayeon";
		int age = 23;
		boolean gender = false;

		String msg = MessageFormat.format("name: {0}, age: {1}, gender: {2}\n", name, age, gender);
		System.out.println(msg);
		//앞으로 String.format대신 이렇게 쓰자
	}

}
반응형

'Java' 카테고리의 다른 글

[days21] 컬렉션 프레임워크  (0) 2020.10.19
[days21] JDK 1.8 java.time  (0) 2020.10.19
[days20] 날짜와 시간  (0) 2020.10.18
[days19] Math클래스, 래퍼클래스, java.util.Objects  (0) 2020.10.18
[문제] 수박수박  (0) 2020.10.18
Comments