지식보부상님의 공부 일지

[3] 출력 print, println, printf 본문

JAVA를 자바

[3] 출력 print, println, printf

지식보부상님 2020. 12. 29. 00:11

C 언어에서 콘솔창에 출력하려면 printf 를 쓰죠??

자바에서는 System.out.print, System.out.println, System.out.printf 가 있답니다!!

 

1. System.out.print

줄바꿈 없이 출력하는 메소드에요!

1
2
System.out.print("I have two dogs, ");
System.out.print("porong and darong");
cs

라고 작성하면 출력 결과는

 

와 같습니다.

 

2. System.out.println

해당 String을 출력하고 줄바꿈 해주는 메소드에요!

1
2
System.out.println("I have two dogs, ");
System.out.println("porong and darong");
cs

라고 작성하면 출력 결과는

다음과 같이 두 줄로 출력됩니다!

 

1
2
3
int n = 2;
System.out.println("I have "+ n +" dogs, ");
System.out.println("porong and darong");
cs

와 같이 다른 타입이어도 +로 연결하여 작성할 수 있어요!  (System.out.print도 마찬가지)

결과는

위와 같겠네용!

3.  System.out.printf

C언어의 printf와 같은 역할을 해요!

printf 의 문법과 동일합니다!

 

1
2
3
int n = 2;
System.out.printf("I have %d dogs, ", n);
System.out.printf("porong and darong");
cs

와 같은 코드를 작성하면

출력 결과는 

위와 같습니다.

 

++ 

%d : 정수(integer)

%x : 16진수(hexadecimal number)

%f : 실수(floating point)

%c : 문자(character)

%s : 문자열(string)

%b : boolean

을 나타냅니다.

 

또한, 

+ :  부호를 보여줌

- : 왼쪽 정렬

0 : 숫자 앞에 0으로 채움

( : - 부호 대신에 괄호 (웃는 것 처럼 보이네)

, : 3자리 마다 콤마(,) 찍어줌

 

등의 flag들이 존재합니다!

예를 들어 하나만 볼까요?

1
2
3
int n = -2;
System.out.printf("I have %(d dogs, ", n);
System.out.printf("porong and darong");
cs

 

라고 작성하면

라는 출력이 나옵니다!

'JAVA를 자바' 카테고리의 다른 글

[6] do~while loop  (0) 2020.12.29
[5] 랜덤 숫자 Math.random  (0) 2020.12.29
[4] if 문  (0) 2020.12.29
[2] user input을 받는 Scanner 클래스와 nextLine, nextInt, nextDouble, next  (0) 2020.12.28
[1] 문자열(String)  (0) 2020.12.28