'객체 배열'에 해당되는 글 1건

끝말잇기 게임

Develope/Java 2020. 5. 14. 00:55
반응형

JAVA를 이용하여 끝말잇기 게임을 만들어보았다.


아래는 개발 시의 조건들이다.


1. 참가인원을 입력받을 것

2. 참가 인원 수대로 이름을 입력받을 것

3. 끝말잇기 게임 진행

4. 패배한 인원의 이름을 출력할 것


아래는 프로그램 실행 결과이다.

이 것을 참고하여 여러분들도 직접 코딩해볼 것을 추천한다.


다음은 내가 작성한 코드이다.

직접 작성한 코드와 비교해보고 자신의 코드가 더 효율적이라 생각이 된다면 댓글로 부탁드립니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.Scanner;
 
class Player{
    String name="";
    String sayWord(){
        Scanner input = new Scanner(System.in);
        String word = input.nextLine();
        return word;
    }
    int succeed(String word,String compare){
        int result=0;
        
        int lastIndex = compare.length()-1;
        char lastChar = compare.charAt(lastIndex);
        char firstChar = word.charAt(0);
        
        
        if(firstChar==lastChar)
            result=1;
        else
            result=0;
        
        return result;
    }
}
 
public class WordGameApp {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("게임에 참가하는 인원은 몇명입니까>>");
        int playerCount = input.nextInt();
        Player[] playerList = new Player[playerCount];
        
        for(int i=0; i<playerCount; i++){
            System.out.print("참가자의 이름을 입력하세요>>");
            playerList[i] = new Player();
            playerList[i].name=input.next();
        }
        
        System.out.println("시작하는 단어는 아버지입니다");
        String FirstWord="아버지";
        
        int i=0;
        String compare=FirstWord;
        while(true){
            System.out.print(playerList[i].name+">>");
            String word = playerList[i].sayWord();
            if(playerList[i].succeed(word, compare)==1){
                i++;
                compare=word;
                if(i==playerCount) i=0;
                continue;
            } else {
                System.out.println(playerList[i].name+"이 졌습니다.");
                System.exit(1);
            }
        } 
    }
}
 
cs


** 코드를 작성하며 배운 것

1. 객체 배열을 생성 시 레퍼런스만 생성된 것이다.

 - main 함수에서 Player[] playerList = new Player[playerCount]; 을 하였을 때에는 Player라는 객체를 가리키는 레퍼런스들을 원소로 하는 배열이 생성된 것이다.

 - 각 원소별로 Player 객체를 가리키도록 playerList[i] = new Player(); 을 선언해주어야 한다.

반응형

'Develope > Java' 카테고리의 다른 글

Java의 정석 정리 - 2장 변수 (문자형)  (0) 2020.06.28
Java의 정석 정리 - 1장 자바를 시작하기 전에  (0) 2020.06.28
final  (0) 2020.05.11
static 멤버  (0) 2020.05.11
접근 지정자  (0) 2020.05.10
블로그 이미지

rootable

,