- 자바 표준출력 메소드
println(); , print();
println(); 개행O
print(); 개행X
class Main{
public static void main(String[] args) {
System.out.print("월요일입니다.");
System.out.println();
System.out.print("안녕자바");
// 개행없음
System.out.println(2022); // 정수
System.out.println(3.14); // 실수
System.out.println('A'); // 문자
System.out.println("ㄱㄴㄷ"); // 문자열
System.out.println("20"+"22"); // 문자열합치기
System.out.println(20+22); // 연산
System.out.println(4+4+"");
System.out.println(4+""+4);
System.out.println(" "+4+4);
}
}
/* output
월요일입니다.
안녕자바2022
3.14
A
ㄱㄴㄷ
2022
42
8
44
44
*/
✅ printf(); 출력형식 지시자
| 지시자 | 설명 |
| %d | 10진(decimal) 정수의 형식으로 출력 |
| %o | 8진(octal) 정수의 형식으로 출력 |
| %x, %X | 16진(hexa-decimal) 정수의 형식으로 출력 |
| %f | 부동 소수점(floating-point)의 형식으로 출력 |
| %e, %E | 지수(exponent) 표현식의 형식으로 출력 |
| %c | 문자(character)로 출력 |
| %s | 문자열(string)로 출력 |
| %b | 불리언(boolean)형식으로 출력 |
| %n | 개행 |
class Main{
public static void main(String[] args){
int exInt = 10;
System.out.printf("exInt는 10진수로 %d%n", exInt);
System.out.printf("exInt는 8진수로 %o%n", exInt);
System.out.printf("exInt는 16진수로 %X%n", exInt);
float exFloat = 10.0f;
System.out.printf("exFloat는 실수로 %f%n", exFloat);
char exChar = 'A';
System.out.printf("exChar는 문자로 %c%n", exChar);
System.out.printf("숫자65는 문자로 %c%n", 65);
System.out.printf("숫자65는 문자열로 %s%n", 65);
System.out.printf("1>2는 boolean으로 %b%n", 1>2);
System.out.printf("1==1은 boolean으로 %b%n", 1==1);
}
}
/* output
exInt는 10진수로 10
exInt는 8진수로 12
exInt는 16진수로 A
exFloat는 실수로 10.000000
exChar는 문자로 A
숫자65는 문자로 A
숫자65는 문자열로 65
1>2는 boolean으로 false
1==1은 boolean으로 true
*/
class Main{
public static void main(String[] args){
int num = 123;
System.out.printf("(%d)%n",num); // (123)
System.out.printf("(%8d)%n",num); // ( 123)
System.out.printf("(%-8d)%n",num); // (123 )
System.out.printf("(%08d)%n",num); // (00000123)
float pi = (float)Math.PI;
System.out.printf("(%8.4f)%n", pi); // ( 3.1416)
System.out.printf("(%1.4f)%n", pi); // (3.1416)
System.out.printf("(%1f)%n", pi); // (3.141593)
System.out.printf("(%08.4f)%n", pi); // (003.1416)
String str = "Hello.JAVA"; // . 포함 10자
System.out.printf("(%s)%n",str); // (Hello.JAVA)
System.out.printf("(%15s)%n",str); // ( Hello.JAVA)
System.out.printf("(%-15s)%n",str); // (Hello.JAVA )
System.out.printf("(%.4s)%n",str); // (Hell)
}
}
- 괄호는 %-8d의 범위를 보여주기위함
- %8d : 총 8자리를 사용하고 우측정렬, 빈자리는 비움
- %-8d : 총 8자리를 사용하는데 왼쪽부터 채우고 빈자리는 비움
- %08d : 총 8자리사용하고 우측정렬, 빈자리는 0으로채움
- %8.4f : 소수점포함 총 8자리를 사용하고 소수점아래 4자리까지 표현
- %1f : 소수점포함 총 1자리를 사용하지만 다 float이 갖는값 다 나옴
- %08.4f : 소수점포함 총 8자리를 사용하고 빈자리는 0으로 채움
- %15s : 총 15자리를 사용
- %-15s : 총 15자리를 사용 좌측정렬
- %.4s : 앞에서 네개까지만 나옴
'Java' 카테고리의 다른 글
| JAVA - 문자열 분리 ( StringTokenizer ) (0) | 2022.06.29 |
|---|---|
| JAVA - 문자열 분리 ( split ) (0) | 2022.06.28 |
| JAVA - 입력받기 ( BufferedReader ) (0) | 2022.06.27 |
| JAVA - 입력받기 ( Scanner.next, nextLine ) (0) | 2022.06.26 |
| JAVA - 역슬래시 ( \ ) (0) | 2022.06.26 |