본문 바로가기
Programming/Algorithm

[백준] 10950번 : A+B-3 (Java)

by 안녕주 2021. 7. 9.

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 테스트 케이스의 개수 T가 주어진다.

각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)

출력

각 테스트 케이스마다 A+B를 출력한다.


코드

import java.util.*;
public class Main{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int tc;
        tc = sc.nextInt();

        int arr[] = new int[tc];
        
        for (int i = 0; i <tc; i++){
            int a = sc.nextInt();
            int b = sc.nextInt();
            arr[i] = a+b;
        }

        for (int j = 0; j < tc; j++){
            System.out.println(arr[j]);
        } 
    }   
}

풀이

자바를 오랜만에 하는지라 배열을 선언할때 뭔가 까다로운 조건이 있었던걸로 기억해서 구글링을 통해 문제를 풀었다.

배열은 변수와 마찬가지로 자료형을 함께 선언한다.

/*기본 형태*/
자료형[] 배열이름 = new 자료형[개수];
자료형 배열이름[] = new 자료형[개수];

/*가능한 경우*/
int[] studentIDs = new int[10];
int[] studentIDs = new int[] {101,102,103};
int[] studentIDs = {102,102,103} //int형 요소가 3개인 배열 생성
int[] studentIDs; //배열 자료형 선언
studentIDs = new int[] {101,102,103}; //new int[]를 생략할 수 있음

/*오류 발생*/
int[] studentIDs = new int[3] {101,102,103}; //오류 발생, 값을 넣어 초기화할 때 []안에 개수를 쓰면 오류

댓글