Java
[프로그래머스] 2. a와 b 출력하기
lemonarr🍋
2024. 4. 3. 21:16
나의 문제풀이
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 = " + a + "\n" + "b = "+ b);
}
}
다른사람의 문제풀이 1
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 = " + a);
System.out.println("b = " + b);
sc.close();
}
}
System.out.println() 두 개를 나누어서 작성이 되는건지 모르고 냅다 줄바꿈 기능인 \n을 사용했다.
Scanner 객체는 사용 후 close() 메서드를 호출하여 자원을 해제해야 한다.
자원 누수를 방지하기 위함이라고 한다.
다른사람의 문제풀이 2
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("a = %d", a));
System.out.println(String.format("b = %d", b));
}
}
%d 지시자
a = %d , a
a = %d는 a의 값이 정수라고 가정하고, 그 값을 문자열 내에 삽입한다.
String.format() 메서드는 지정된 포맷 문자열과 인자를 사용하여 새로운 문자열을 생성합니다.
이 메서드는 다양한 데이터 타입을 문자열로 변환하고, 특정 형식에 맞게 조정하는 데 유용합니다.