▶ 문제
https://www.acmicpc.net/problem/1330
1330번: 두 수 비교하기
두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오.
www.acmicpc.net
▶ 설명
두 개의 수를 입력 받아 비교 결과를 출력하는 문제이다.
▶ 문제 풀이
🌱 풀이1. if문 사용
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
br.close();
StringTokenizer strTo = new StringTokenizer(str, " ");
int a = Integer.parseInt(strTo.nextToken());
int b = Integer.parseInt(strTo.nextToken());
if(a>b) System.out.println(">");
else if(a<b) System.out.println("<");
else System.out.println("==");
}
}
출력물의 경우의 수는 3가지이고, if문을 이용해 하나씩 조건을 만들어주었다.
가장 손 쉬운 방법이다.
🌱 풀이2. 삼항 연산자 사용
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
br.close();
StringTokenizer strTo = new StringTokenizer(str, " ");
int a = Integer.parseInt(strTo.nextToken());
int b = Integer.parseInt(strTo.nextToken());
System.out.println((a>b) ? ">" : ((a<b) ? "<" : "=="));
}
}
if문 대신 삼항 연산자를 이용할 수도 있다.
처음에는 낯설지만 계속 사용하다보면 간결하고 쉬운 코드가 될 수 있을 것 같다.
▶ Log
728x90
반응형
'백준 알고리즘 > 조건문' 카테고리의 다른 글
백준 2408 :: 주사위 세개 [JAVA] (0) | 2022.05.19 |
---|---|
백준 2525번 :: 오븐 시계 (0) | 2022.05.18 |
백준 2884번 :: 알람 시계 (0) | 2022.05.18 |
백준 14691번 :: 사분면 고르기 (0) | 2022.05.17 |
백준 9498번 :: 시험 성적 (0) | 2022.05.16 |