본문 바로가기
수업(국비지원)/Java

[Java] chap11: 기본 API(패키지 클래스) - 기본 API Exam 4-5 (format 메서드, 함수 구현)

by byeolsub 2023. 4. 16.

📌 기본 API Exam4. (format 메서드)

package chap11;
/*
 * format 메서드 구현하기
 * 메서드명 : String format (String str,int len,int align)
 * 기능 : 주어진 문자열을 지정된 크기(len)의 문자열로 변환.
 *        나머지 공간은 공백으로채운다.
 *      (0 : 왼쪽 정렬, 1: 가운데 정렬, 2:오른쪽 정렬)       
 */
public class Exam4 {
	public static void main(String[] args) {
		String str = "가나다";
		System.out.println(format(str, 7, 0));//가나다
		System.out.println(format(str, 7, 1));//  가나다  
		System.out.println(format(str, 7, 2));//    가나다
		System.out.println(format(str, 2, 0));//가나
	}
	static String format (String str,int len,int align) {
		if(str.length() >= len)
			return str.substring(0,len);
		
		//str.length() < len 경우
		StringBuffer sb = new StringBuffer();
		//sb="       "
		for(int i=0;i<len;i++)
			sb.append(" ");
		
		int l = len - str.length(); //7 - 3 = 4
		switch(align) {
		case 0 : sb.replace(0, str.length(), str); break; //왼쪽 정렬
		case 1 : sb.replace(l/2, str.length()+l/2, str); break; //가운데
		case 2 : sb.replace(l, str.length()+l, str); break;  //오른쪽
		}
		return sb.toString();
	}
}

📌 기본 API Exam5. (함수 구현)

package chap11;
/* 함수 구현하기
 * double round(실수형,소숫점이하 자리수) 
 * double truncate(실수형,소숫점이하 자리수) 
 */
public class Exam5 {
	public static void main(String[] args) {
		System.out.println(round(3.1215,1)); //3.1
		System.out.println(round(3.1215,2)); //3.12
		System.out.println(round(3.1215,3)); //3.122
		System.out.println(round(3.1215,4)); //3.1215
		System.out.println(truncate(3.15345,1)); //3.1
		System.out.println(truncate(3.15345,2)); //3.15
		System.out.println(truncate(3.15345,3)); //3.153
		System.out.println(truncate(3.15345,4)); //3.1534
	}
	static double round(double d, int i) {
		//"%.2f" 
		String sf = String.format("%."+i+"f", d);
		return Double.parseDouble(sf);
	}
	static double truncate(double d, int i) {
		int num10=1;
		for(int a=0;a < i;a++) {
			num10 *=10; 
		}
		return (int)(d*num10)/(double)num10;
	}
}