Displaying text in Java (println and printf)
println
e.g) System.out.println("Hello World" + 변수명)
'+' 을 사용하면 변수명과 문자열(" " 사용) 을 동시에 사용할 수 있다.
자동줄바꿈기능
printf
e.g) System.out.printf("Hello World %d",변수명)
format specifier 를 사용해서 다른 형식의 출력을 허용한다.
자동 줄바꿈이 되지 않음
Printf format specifier
Format Specifier |
Description |
%d |
integer 정수 출력 |
%f |
Decimal format 소수점 출력 |
%c |
Character 문자 출력 |
%s |
String 문자열 출력 |
%n | line separator 줄바꿈 |
HackerRank Java Output Formatting
Question
The first column contains the String and is left justified using exactly characters.
The second column contains the integer, expressed in exactly digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("================================"); for(int i=0;i<3;i++){ String s1=sc.next(); int x=sc.nextInt(); System.out.printf("%-15s%03d%n",s1,x); } System.out.println("================================"); } } | cs |
System.out.printf("%-15s%03d%n",s1,x);
%-15s '-' (left-justifying) 을 이용해 왼쪽정렬로 15칸
%03d '0' 0으로 정수의 빈칸을 매워주기
%n 줄바꿈
output
1 2 3 4 5 6 | Expected OutputDownload ================================ java 100 cpp 065 python 050 ================================ | cs |
Reference
Hackerrank (https://www.hackerrank.com/)