서식 문자열을 모르는 바보가 있다? 그게 바로 저에요~~~
두 정수 a, b가 주어질 때 다음과 같은 형태의 계산식을 출력하는 코드를 작성해 보세요.
a + b = c
1 ≤ a, b ≤ 100
4 5
4 + 5 = 9
위와 같은 문제를 푸는데 멋쟁이 개발자처럼 서식 문자열로 출력하고 싶었다!
근데
System.out.println(a + " + " + b + " = " + (a+b));
이렇게 쓰니까 안된다? 당연히 안 된단다.
System.out.printf("%d + %d = %d",a,b,a+b);
printf()를 써야한단다?
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
//System.out.println(a + b);
System.out.println(a + " + " + b + " = " + (a+b));
}
}
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.printf("%d + %d = %d",a,b,a+b);
}
}
일반 문자가 아닌 서식에 사용되는 문자를 서식 문자라고 한다.
%d : 10진수 (정수)
%o : 8진수
%x : 16진수
%f : 실수
%c : 문자
%s : 문자열
printf() 에 대입해서 사용가능하다!