📌 기본 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;
}
}
'수업(국비지원) > Java' 카테고리의 다른 글
| [Java] chap12: 기본 API - 기본 API Exam1 (0) | 2023.04.16 |
|---|---|
| [Java] chap12: 기본 API - Random (0) | 2023.04.16 |
| [Java] chap11: 기본 API(패키지 클래스) - Wrapper (0) | 2023.04.16 |
| [Java] chap11: 기본 API(패키지 클래스) - Math (0) | 2023.04.16 |
| [Java] chap11: 기본 API(패키지 클래스) - 기본 API Exam3.(delChara메서드 구현) (0) | 2023.04.16 |