[BAEKJOON] 조건문 1330번 - 두 수 비교하기

밍챠코·2024년 3월 12일
0

BAEKJOON

목록 보기
12/38

📝1330

[Java]

1. Scanner 이용

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        int A = sc.nextInt();
        int B = sc.nextInt();
        
        if(A>B) {
        System.out.print(">");
        } else if(A<B) {
        System.out.print("<");
        } else {
        // else if (A == B) {
        System.out.print("==");
        }
        
        sc.close();
    }
}

💡 A==B를 쓰는 이유?
→ if문은 True or False만 판별하기 때문에 "=="를 사용하게 되면 boolean 즉 참/거짓 판별 가능

💡 조건(삼항)연산자 이용

조건식 ? 참값 : 거짓값
→ 조건식 결과가 true일 때 참값 반환, false이면 거짓값 반환

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        int A = sc.nextInt();
        int B = sc.nextInt();
        
        String str = (A>B) ? ">" : ((A<B) ? "<" : "==" );
        System.out.print(str);
        
        sc.close();
    }
}

2. BufferedReader 이용

💡 StringTokenizer 클래스를 이용하여 문자열 분리

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();
        StringTokenizer st = new StringTokenizer(str, " ");
        //StringTokenizer st = new StringTokenizer(br.readLine()," ");
        
        int A = Integer.parseInt(st.nextToken());
        int B = Integer.parseInt(st.nextToken());
        
        System.out.print((A>B) ? ">" : ((A<B) ? "<" : "=="));
        
        br.close();
    }
}

[Javascript]

const input = require('fs').readFileSync('/dev/stdin').toString().trim().split(' ').map(Number);

const[A, B] = input;
// const[A, B] = [input[0], input[1]];

if(A < B){
    console.log('<');
} else if(A > B){
    console.log('>');
} else {
// else if (A == B) {
    console.log('==');
}
const input = require('fs').readFileSync('/dev/stdin').toString().trim().split(' ').map(Number);

const A = input[0];
const B = input[1];

console.log(A>B ? ">" : A<B ? "<" : "==");

[Python]

A, B = map(int, input().split())
if A>B :
    print(">")
elif A<B :
    print("<")
else:
#elif A==B :
    print("==")

💡 조건(삼항)연산자 이용

삼항 표현식 문법 : 참값 if 조건문 else 거짓값

중첩 삼항 표현식 : 참값 if 조건문1 else [ 참값2 if 조건문2 else 거짓값 ]

A, B = map(int, input().split())
print(">") if A>B else print("<") if A<B else print("==")

0개의 댓글