본문 바로가기

Java/코딩테스트

[Java/Bronze V] 킹, 퀸, 룩, 비숍, 나이트, 폰 - 3003, 배열, Scanner 클래스, for문

문제 설명

동혁이는 오래된 창고를 뒤지다가 낡은 체스판과 피스를 발견했다.

체스판의 먼지를 털어내고 걸레로 닦으니 그럭저럭 쓸만한 체스판이 되었다. 하지만, 검정색 피스는 모두 있었으나, 흰색 피스는 개수가 올바르지 않았다.

체스는 총 16개의 피스를 사용하며, 킹 1개, 퀸 1개, 룩 2개, 비숍 2개, 나이트 2개, 폰 8개로 구성되어 있다.

동혁이가 발견한 흰색 피스의 개수가 주어졌을 때, 몇 개를 더하거나 빼야 올바른 세트가 되는지 구하는 프로그램을 작성하시오.

 

 

 

주요 사용 개념

배열

⚠️배열은 같은 타입의 데이터만 저장할 수 있습니다. (int 배열은 int 값만 저장, String 배열은 문자열만 저장합니다.)
한 번 생성된 배열의 길이를 늘리거나 줄일 수 없습니다. 

  • 배열 선언
    • 타입[ ] 변수;
  • 배열 생성
    • 값 목록으로 배열 생성: 타입[ ] 변수 = {값1, 값2, ...};
    • new 연산자로 배열 생성
      타입[ ] 변수 = null;
      변수 = new 타입[길이];
  • 사용 예시
// 올바른 체스 피스
int[] chessPieces = {1, 1, 2, 2, 2, 8};
// 찾은 체스 피스
int[] foundPieces = new int[chessPieces.length];
  • 타입별 배열의 초기값
분류 타입 초기화
기본 타입(정수) byte[ ]
char[ ]
short[ ]
int[ ]
long[ ]
0
'\u000'
0
0
0L
기본 타입(실수) float[ ]
double[ ]
0.0F
0.0
기본 타입(논리) boolean[ ] false
참조 타입 클래스[ ]
인터페이스[ ]
null
null

 

Scanner 클래스

⚠️nextInt(), nextDouble()과 같은 메소드 사용 시에는 입력 버퍼에 남아있는 개행 문자로 인해 제대로 작동하지 않는 일을 방지하기 위해 sc.nextLine()을 한 번 더 호출해서 버퍼를 비워주는 것이 좋습니다.
  • 정의
    • Java에서 표준 입력으로부터 데이터를 읽을 때 사용되는 도구로, 다양한 자료형의 데이터를 읽을 수 있습니다.
  • 객체 생성
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
  • 주요 메소드
종류 내용
nextLine() 문자열 한 줄 입력받기
nextInt() 정수 입력 받기
nextDouble() 실수 입력 받기
next() 공백 전까지의 문자열 입력 받기 (단어)
  • 사용 예시
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
    	Scanner sc = new Scaaner(System.in);
        
        System.out.print("이름을 입력하세요: ");
        String name = sc.nextLine(); // 한 줄 전체 입력 받기
        System.out.println("입력한 이름: " + name);
        
        System.out.print("숫자를 입력하세요: ");
        int number = sc.nextInt(); // 정수 입력 받기
        sc.nextLine(); // 입력 버퍼 비우기
        System.out.println("입력한 숫자: " + number);
        
        System.out.print("몸무게를 입력하세요: ");
        double weight = sc.nextDouble(); // 실수 입력 받기
        sc.nextLine(); // 입력 버퍼 비우기
        System.out.println("입력한 몸무게: " + weight);
		
        sc.close();
    }
}
        // 찾은 체스 피스
        int[] foundPieces = new int[chessPieces.length];
        for (int i =0; i < chessPieces.length; i++) {
            foundPieces[i] = sc.nextInt();
        }

 

for문

  • 기본 구조
for (초기치; 조건문; 증가치) {
	...
}
        // 찾은 체스 피스
        int[] foundPieces = new int[chessPieces.length];
        for (int i =0; i < chessPieces.length; i++) {
            foundPieces[i] = sc.nextInt();
        }

        // 차이 계산 및 출력
        for (int i = 0; i < chessPieces.length; i++) {
            int diff = chessPieces[i] - foundPieces[i];
            if (i == chessPieces.length - 1) {
                System.out.println(diff);
            } else {
                System.out.print(diff + " ");
            }
        }
  • continue
    • for문 안의 문장을 수행하는 도중에 continue를 만나면 for문의 처음으로 돌아갑니다.
int[] marks = {90, 25, 67, 45, 80};
for(int i=0; i<marks.length; i++) {
    if (marks[i] < 60) {
        continue;  // 조건문으로 돌아간다.
    }
    System.out.println((i+1)+"번 학생 축하합니다. 합격입니다.");
}
  • 이중 for문
for(int i=2; i<10; i++) {
    for(int j=1; j<10; j++) {
        System.out.print(i*j+" ");
    }
    System.out.println("");  // 줄을 바꾸어 출력하는 역할을 한다.
}

 


 

code

/**
 * 문제 링크: https://www.acmicpc.net/problem/3003
 * 시간: 184 ms
 * 메모리: 18308 KB
 */
package BOJ;

import java.util.Scanner;

public class B3003 {
    public static void main(String[] args) {
        // 킹, 퀸, 룩, 비숍, 나이트, 폰의 값을 input 받기
        Scanner sc = new Scanner(System.in);

        // 올바른 체스 피스
        int[] chessPieces = {1, 1, 2, 2, 2, 8};
        // 찾은 체스 피스
        int[] foundPieces = new int[chessPieces.length];
        for (int i =0; i < chessPieces.length; i++) {
            foundPieces[i] = sc.nextInt();
        }

        // 차이 계산 및 출력
        for (int i = 0; i < chessPieces.length; i++) {
            int diff = chessPieces[i] - foundPieces[i];
            if (i == chessPieces.length - 1) {
                System.out.println(diff);
            } else {
                System.out.print(diff + " ");
            }
        }
        sc.close();
    }
}

 

 


Github

 

참고자료

반응형