자바의 출력에 대해 간단히 알아보자.
1. 서식 없는 출력
System.out.print() : 괄호 안의 내용을 출력하고 줄을 바꾸지 않는다.
System.out.println() : 괄호 안의 내용을 출력하고 줄을 바꾼다.
1
2
3
4
5
6
7
8
9
10
11
12
|
public class forTistory {
public static void main(String[] args) {
System.out.println("안녕 \n자바");
System.out.println("안녕 자바");
}
}
|
cs |
2. "+" 연산자 이용
"+" 연산자는 양쪽 데이터가 모두 숫자일 경우 덧셈을 하고 한쪽이라도 문자열이면 문자열끼리 연결하는 문자열 연결 연산자로 사용된다.
1
2
3
4
5
6
7
8
9
10
|
System.out.println("5 + 3 = " + (5 + 3));
System.out.println("5 - 3 = " + (5 - 3));
System.out.println("5 * 3 = " + 5 * 3); // "*" , "/" 는 "+" 연산자보다 먼저 실행되므로 굳이 괄호를 써주지 않아도 된다.
System.out.println("5 / 3 = " + 5 / 3);
System.out.println("5 / 3 = " + (double) 5 / 3); // 소수점까지 나타내고 싶다면!
System.out.println("5 % 3 = " + 5 % 3); // 몫
System.out.println("===================================");
|
cs |
3. 서식 있는 출력
System.out.printf("서식 문자", 출력할 데이터);
1
2
3
4
5
6
7
8
9
10
|
// 사용 방법은 c/c++ 과 같다
// System.out.printf("서식 문자", 출력할 데이터);
System.out.printf("%d + %d = %d\n", 5, 3, 5 + 3);
System.out.printf("%d - %d = %d\n", 5, 3, 5 - 3);
System.out.printf("%d * %d = %d\n", 5, 3, 5 * 3);
System.out.printf("%d / %d = %d\n", 5, 3, 5 / 3);
System.out.printf("%d / %d = %f\n", 5, 3, 5 / 3.);
System.out.printf("%d / %d = %f\n", 5, 3, (double) 5 / 3);
System.out.printf("%d %% %d = %d\n", 5, 3, 5 % 3);
|
cs |
++ 추가로,,
1
2
|
// 자바가 printf() 메소드를 지원하지 않을 때, 사용하는 서식 있는 출력 방식 => String.format("서식 문자", 출력할 데이터)
System.out.println(String.format("%d + %d = %d\n", 5, 3, 5 + 3));
|
cs |
'Java' 카테고리의 다른 글
자바/JAVA/Thread/스레드 (0) | 2020.01.29 |
---|---|
JAVA/자바/SimpleDateFormat/substring/charAt (0) | 2020.01.20 |
JAVA/자바/Calendar 클래스/ (0) | 2020.01.20 |
JAVA/자바/날짜&시간 출력/SimpleDateFormat (0) | 2020.01.20 |
JAVA/자료형/자바의기본자료형과 String (0) | 2020.01.17 |