일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 스프링
- 파이썬
- 스파르타 코딩클럽
- 수정자주입
- 원티드프리온보딩백엔드챌린지
- 의존성자동주입
- 캐치
- 도커
- 자바
- 벨로그
- Java
- 스파프타 코딩클럽
- springboot
- 인텔리제이
- 필드주입
- 원티트 프리온보딩
- 웹크롤링
- docker
- 알고리즘
- commit message
- 원티드 백엔드 챌린지
- 자료구조
- 생성자주입
- velog
- 개발자 커리어콘
- 커밋메세지
- Spring
- 프리온보딩 4월 백엔드 챌린지
- 의존성주입
- 원티드 챌린지
- Today
- Total
기록하는 블로그
[Java] 출력 포맷 설정하기 본문
처음 자바를 배웠을 때부터 항상 헷갈리는 부분인데 매번 대충 찾아보고 정리를 안 하고 넘어갔다니 자꾸 발목을 잡는다. 이번 기회에 확실하게 정리하고자 마음먹고 기록해보기로 했다. 오늘이 진짜 마지막이다......
1. System.Out.Println ( );
가장 기본적인 출력 방법이다. 자바를 잘 몰랐을때는 " System.out.println(); " 이걸 하나의 고유 명사? 처럼 사용했었는데, 다른 일반적인 클래스를 사용하는 것과 동일하다.
먼저 System 이라는 클래스는 Java Doc에서 이렇게 설명하고 있다. (Java 11 기준)
(docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/System.html)
위의 링크로 들어가서 볼수도 있지만 Eclipse에서 맥은 Command, 윈도우는 Ctrl을 누른 채 해당 코드를 누르면 볼 수 있다.
먼저 System 이라는 클래스를 알아보기로 했다.
public final class System
extends Object
The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
일단 Object를 상속받고 있고 표준 입출력과 에러 출력, 외부에서 정의된 설정이나 변수로 접근, 파일과 라이브러리의 로딩 수단, 배열의 일정 부분을 빠르게 카피하는 수단이라고 쓰여 있는 것 같다.
다음은 Out 이다.
System 클래스에는 3가지 필드가 있는데, 그중 하나가 Out 이다.
public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println methods in class PrintStream.
표준 출력 스트림이고 이미 열려있고 출력할 데이터를 받아들일 준비가 되어있으며 전형적으로 사용자가 지정한 출력 목적지나 결과물을 표시하는 것과 일치한다.라고 해석했는데 무슨 뜻인지 명확히는 모르겠으면 그냥 표준 출력 스트림이다 정도만 기억하면 될 것 같다.
그리고 우리가 가장 많이 봤던 형식으로 사용한다라고 나와있다. 더 알아보고 싶어서 PrintStream에 대해서 찾아보기로 했다.
public class PrintStream
extends FilterOutputStream
implements Appendable, Closeable
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.
All characters printed by a PrintStream are converted into bytes using the given encoding or charset, or platform's default character encoding if not specified. The PrintWriter class should be used in situations that require writing characters rather than bytes.
This class always replaces malformed and unmappable character sequences with the charset's default replacement string. The CharsetEncoder class should be used when more control over the encoding process is required.
해석 :
printstream은 다른 출력 스트림으로 기능을 추가한다. 즉 다양한 데이터의 값을 편리하게 출력해서 표현하는 기능이다. 두 가지의 다른 기능들도 또한 제공된다. 다른 출력 스트림과는 다르게 printstream은 절대로 IOException을 throws 하지 않는다. 대신, 예외적인 상황에서 checkError 메서드로 테스트할 수 있는내부적인 flag를 설정한다. 선택적으로 printstream으로 자동적으로 flush 하도록 만들어질 수 있다.
이것은 flush 메서드가 바이트 배열이 쓰인 다음 자동적으로 호출되고, println 메서드들 중 하나가 호출되거나 개행 문자가 쓰이는 것을 말한다.
printstream으로 프린트된 모든 문자들은 주어진 인코딩, 문자 인코딩(charset), 정의되어 있지 않다면 플랫폼의 기본 문자 인코딩으로 변환된다. PrintWritter 클래스는 바이트가 아니라 문자를 쓰는 상황에서 쓰여야 한다.
이 클래스는 형태가 잘못되거나, 문자 인코딩의 기본 대체 문자열과 매핑할 수 없는 문자열들을 항상 다른 것으로 바꾼다. CharsetEncoder class는 인코딩 과정에서 더 많은 제어를 해야 할 때 사용되어야 한다.
그리고 이 클래스의 필드로 선언되어 있는 out을 볼 수 있다.
2. System.Out.Print ( );
print는 기본적으로 println과 같지만 개행이 안된다는 점이 다르다. println은 출력을 하면 기본적으로 다음 줄에 출력되지만 print는 공백 없이 이어서 출력된다.
3. System.Out.Printf ( );
사실 이 글을 쓰려고 마음먹은 가장 큰 이유는 바로 이것 때문이다. Prinf는 위에서 본 PrintStream의 메서드 중 하나이다.
해석하자면, 특정 문자열 양식과 인자들을 활용해서 양식이 있는 문자열을 편리하게 작성 있게 해주는 메서드라는 뜻이다.
스크린샷의 두 번째 줄에 있는 Locale은 특정의 지리적, 국가적, 또는 문화적 지역을 나타내기 위한 객체인데 예를 들면 국가별 화폐를 사용할 때 사용할 수 있다.
printf는 출력하는 값의 타입에 따라 그것을 나타내는 지시자를 함께 사용할 수 있다.
지시자 | 값의 타입 |
%d | 부호있는 정수로 출력 |
%u | 부호 없는 정수로 출력 |
%f | 실수로 출력 |
%s | 문자열로 출력 (String) |
%c | 문자로 출력 (Character) |
%b | boolean 형식으로 출력 |
이외에도 몇 가지 더 있는데 자주 사용하는 것만 작성해봤다.
개인적으로 가장 많이 사용하는 것은 특정 형식으로 표현했던 정수와 실수의 자릿수 표현이지 않을까 싶다.
그래서 이 두 가지의 작성법을 살펴보겠다.
package test;
public class Format_test {
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = 3;
double d = 3.14159265359;
String str = "PrintStream";
System.out.printf("%5d %5d %5d\n", a, b, c);
System.out.printf("%20.6f\n", d);
System.out.printf("%10.6f\n", d);
System.out.printf("%.1s\n", str);
System.out.printf("%.5s\n", str);
System.out.printf("%.10s\n", str);
System.out.printf("%.11s\n", str);
System.out.printf("%5d %10.6f %.5s",a,d,str );
}
}
결과 :
첫 번째 줄은 지시자를 씀으로써 우리가 원하는 int형의 파라미터를 넣을 위치를 정해줬고 그 위치로 차례대로 들어간 모습니다.
% 와 지시자를 나타내는 단어 사이에 숫자를 넣으면 그 숫자만큼의 자리를 만들 수 있다. 그 결과 콘솔에 각 숫자 별로 5칸의 공백이 생겼다.
그리고 개행을 나타내는 \n 을 붙혀서 다음줄로 넘어간 모습니다.
두 번째와 세 번째 줄은 %다음에 오는 숫자만큼 자리를 만들어 주고 실수의 값중 소숫점 아래 6번째 자리까지만 출력한 모습이다.
세번째 줄부터는 문자열의 자리를 만들어 주고 원하는 만큼을 출력해준 모습이다.
그리고 마지막 줄처럼 혼합해서 써줄수도 있다.
--------------
이 글로써 마무리 하려고 했지만 String.format과 조합해서 사용할때 햇갈려서 내용을 추가했다.
package test;
public class String_format {
public static void main(String[] args) {
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 주어진 문자열을 그대로 출력
System.out.printf(String.format("%s\n", str));
// 30칸을 만들고 좌측에서부터 공백을 채움
System.out.printf(String.format("%30s\n", str));
// 30칸을 만들고 우측에서부터 공백을 채움
System.out.printf(String.format("%-30s\n", str));
// 30칸을 만들고 . 우측의 숫자만큼(4) 문자열을 잘라서 죄측에서부터 공백을 만들어가며 출력
System.out.printf(String.format("%30.4s\n", str));
// 30칸을 만들고 . 우측의 숫자만큼(4) 문자열을 잘라서 우측에서부터 공백을 만들어가며 출력
System.out.printf(String.format("%-30.4s\n", str));
// 이렇게 새로운 문자열 변수안에 할당도 가능하다.
String newStr = String.format("%30s\n", str);
System.out.println(newStr);
for(int i =0 ; i < 4; i++) {
System.out.printf(String.format("%%%ds*\n", 10), "");
}
}
}
마지막 반복문 쪽은 아직 왜그런지 모르겠다. 왜 & 기호가 4개나 붙는걸까?
현재까지 알아낸 사실은 %d 에서 10칸을 만들고, %s 에 *표를 넣는것.
'Java' 카테고리의 다른 글
[자료구조] HashMap 정리하기 (0) | 2021.07.28 |
---|---|
[자료구조] Queue 공부하기 (0) | 2021.05.11 |
[지료구조] ArrayList에 대해서 (0) | 2021.05.09 |
[Java] 생성자, Constructor (0) | 2021.01.24 |