대학수업/프로그램설계방법론

[10] 프로그램 설계 방법론(자료구조와 배열)

MIRIP 2022. 10. 13. 14:45
반응형

배열(array) :

  • 동일한 타입의 값을 정해진 개수만큼 나란히 이어 붙여 놓은 구조
int[] r; //null
int[] r = new int[6];
  • 배열(array)는 객체(object)

각 타입의 초기값

  • 배열 생성 시 각 원소는 기본값으로 초기화된다
  • 인덱스(index)는 정수로 0부터 시작한다
  • 배열의 크기가 6이면, 인덱스의 범위는 0~5이다
int [] s = r;

위의 코드는 "r이 갖고 있던 int 배열의 주소를 s도 갖게 하라" 라는 의미이다. 즉, 다음과 같다.

  • 실행 중 범위를 벗어난 인덱스로 배열을 참조하면 ArrayIndexOutOfBoundsException 오류 발생한다
  • 이 오류는 컴파일러가 잡을 수 없다. 프로그램을 만든 사람 책임!!
int[] r = new int[12];

r[0] = 1;
r[1] = 1;
for(int i =2; i<r.length; i++){
    r[i] = r[i-1] + r[i-2];
}

사례 학습 1. 투표 :

import javax.swing.JOptionPane;

public class VoteCount {

	public static void main(String[] args) {
		int num_candidates =4;
		int[] votes = new int[num_candidates];
		
		boolean processing = true;
		while(processing) {
			String input = JOptionPane.showInputDialog("원하는 후보에 투표하세요 : 0, 1, 2, 3");
			if(input == null)
				processing = false;
			else {
				char vote = input.charAt(0);
				if('0'<=vote && vote<='3') {
					int voted = vote - '0';
					votes[voted] +=1;
				}
				else
					System.out.println(input + "은 후보자가 아닙니다.");
			}
		}
		for (int i = 0; i != votes.length; ++i)
			System.out.println("후보" + i + "번이 " + votes[i] + "표를 득표하였습니다.");
	}

}

사례 학습 2. 놀이 카드 :

Model:

public class Card {
	
	public static final String SPADES = "Spades";
	public static final String HEARTS = "Hearts";
	public static final String DIAMONDS = "Diamonds";
	public static final String CLUBS = "Clubs";
	
	public static final int ACE = 1;
	public static final int JACK = 11;
	public static final int QUEEN = 12;
	public static final int KING = 13;
	
	public static final int SIZE_OF_ONE_SUIT = 13;
	
	private String suit;
	private int rank;
	
	public String suit() {return suit;}
	public int rank() {return rank;}
	
	public boolean equls(Card c) {
		return (suit.equals(c.suit()) && rank == c.rank());
	}
}

Card의 속성이기 때문에 Card 클래스가 static final을 갖는 것이 좋다.

 

public class CardDeck {
	
	private Card[] deck;
	private int card_count;
	
	public CardDeck() {
		createDeck();
	}
	
	private void createDeck() {
		createSuit(Card.SPADES);
		createSuit(Card.CLUBS);
		createSuit(Card.HEARTS);
		createSuit(Card.DIAMONDS);
	}
	
	private void createSuit(String _suit) {
		for(int i=1; i<=13; ++i) {
			deck[card_count++] = new Card(_suit, i);
		}
	}
	public Card drawCard() {
		if(card_count==0)
			createDeck();
		int picked = (int)(Math.random() * card_count);
		Card card_drawn = deck[picked];
		for(int i=picked+1; i<card_count; ++i) {
			deck[i-1] = deck[i];
		}
		--card_count;
		return card_drawn;
	}
}

Hand : 

public class Hand {
	
	private Card[] hand;
	private int number_of_cards;
	
	public Hand(int max) {
		hand = new Card[max];
	}
	
	public boolean receiveCard(Card _c) {
		if(number_of_cards < hand.length) {
			hand[number_of_cards++] = _c;
			return true;
		}
		else
			return false;
	}
	
	public boolean playCard(Card _c) {
		boolean found = false;
		int index;
		for(index=0; found==false && index<number_of_cards; ++index) {
			if(hand[index].equls(_c)){
				found = true;
			}
		}
		if(found) {
			for (int i=index+1; i<number_of_cards; ++i)
				hand[i-1] = hand[i];
			--number_of_cards;
			hand[number_of_cards]=null;
			return true;
		}
		else
			return false;
	}
}
728x90
반응형