본문 바로가기
코딩테스트/자바 Java

자바 Java | 화면에 글자 출력하기 | print(), println(), printf()

by YUNI Heo 2023. 2. 15.
반응형

 

✅ 출력

화면에 글자를 출력할 때는 print(), println(), printf()을 사용한다.

 

괄호() 안에 출력하고자 하는 내용을 넣는다.

 

💡 System.out.print();

괄호 안의 내용을 출력하고, 줄 바꿈을 하지 않는다.

 

💡 System.out.println();

괄호 안의 내용을 출력하고, 줄 바꿈을 한다.

 

class Ex2_1 { 
	public static void main(String args[]) { 
		System.out.println("Hello, world");// 화면에 Hello, world를 출력하고, 줄바꿈을 한다.
		System.out.print("Hello");         // 화면에 Hello를 출력하고, 줄바꿈을 하지 않는다.
		System.out.println("World");       // 화면에 World를 출력하고, 줄바꿈을 한다.
	} 
}

 

💡 System.out.printf();

print(), println()은 편리하지만, 값을 변환하지 않고는 다른 형식으로 출력할 수 없다.

 

값을 다른 형식으로 출력하고 싶을 때 printf()를 사용한다.

 

printf()지시자 specifier를 통하여 변환하여 출력한다.

지시자 specifier는 값을 어떻게 출력할 것인지 지시하는 역활을 한다.

 

printf()는 줄바꿈을 하지 않으므로 지시자 %n을 사용한다.

 

  • %d: 10진 decimal 정수형 출력
  • %x: 16진 hexa decimal 정수형 출력
  • %f: 부동 소수점 floating point 출력, 전체자리.소수점아래자리f
  • %c: 문자 character 출력
  • %s: 문자열 string 출력
    • 숫자를 추가하면 원하는 만큼의 출력 공간을 확보한다.
    • 지정된 숫자보다 문자열의 길이가 작으면 빈자리는 공백으로 출력된다.
    • .을 붙이면 문자열의 일부만 출력한다.

 

class Ex2_9 {
	public static void main(String[] args) {
		String url = "www.codechobo.com";
		float f1 = .10f;   // 0.10, 1.0e-1
		float f2 = 1e1f;   // 10.0, 1.0e1, 1.0e+1
		float f3 = 3.14e3f;
		double d = 1.23456789;
		System.out.printf("f1=%f, %e, %g%n", f1, f1, f1); 
		System.out.printf("f2=%f, %e, %g%n", f2, f2, f2); 
		System.out.printf("f3=%f, %e, %g%n", f3, f3, f3);
		System.out.printf("d=%f%n", d);
		System.out.printf("d=%14.10f%n", d); // 전체 14자리 중 소수점 10자리
		System.out.printf("[12345678901234567890]%n");
		System.out.printf("[%s]%n", url);
		System.out.printf("[%20s]%n", url);
		System.out.printf("[%-20s]%n", url); // 왼쪽 정렬
		System.out.printf("[%.8s]%n", url);  // 왼쪽에서 8글자만 출력
	}
}

 

반응형