Study with me/프로그래머스 L0 마스터하기
프로그래머스 - L0 덧셈식출력하기 // print( int → String )
외계나무
2024. 1. 6. 16:08
표준 입출력 클래스 System은 디폴트로 import 되는 java.lang 패키지에 포함되어 있다.
그중 System.out이라는 클래스 변수(static variable)를 사용한 System.out 스트림 System.out.println()
가 대표적인 표준 출력 작업 메서드이다. 이 메서드 자체에는 형변환 기능이 없으므로, 정수와 문자열을 같이 출력하려면 문자열 결합 연산(+)을 통해 자동으로 정수를 문자열로 변환하여 출력해야 한다.
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+" = "+(a+b));
}
}
String.format()
과 지시자(%)를 함께 쓰는 방법도 있다.
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(String.format("%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.printf("%d + %d = %d", a, b, a+b);
}
}