생능출판의 Java Programming 제 4장에 있는 끝말잇기 게임을 타 블로그를 참고하여 코드로 작성해 보았다.
한동안 Java를 아예 손대지 않았더니 정말 다먹었더라... 회계랑 닮았다 안보면 까먹는거.
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
61
62
63
64
65
66
67
68
|
import java.util.Scanner;
class Player{
Scanner scan = new Scanner(System.in);
public String name;
public String word; public String writeWord() {
word = scan.next(); return word;
}
public boolean checkSuccess(char lastChar) {
if (lastChar == wordin.charAt(0)) return true;
else return false;
}
}
public class WordGameApp{
public static void main(String[] args) {
String startword = "아버지";
System.out.println("끝말잇기 게임을 시작합니다...");
System.out.print("게임에 참여하는 인원은 몇명입니까>>> ");
Scanner scan = new Scanner(System.in);
int playernum = scan.nextInt();
Player[] play = new Player[playernum];
for(int i = 0; i<playernum; i++) {
System.out.print("참가자의 이름을 입력하세요>>");
play[i] = new Player();
play[i].name = scan.next();
}
System.out.printf("시작하는 단어는 %s입니다.", startword);
int i = 0, j = 0;
while(true) {
i = j%playernum;
int lastIndex = startword.length() -1;
char lastChar = startword.charAt(lastIndex);
System.out.println(play[i].name + ">> ");
play[i].writeWord();
boolean counting = play[i].checkSuccess(lastChar);
if(counting==false) {
System.out.println(play[i].name + "님이 졌습니다.");
break;
}
startword = play[i].word;
j++;
}
scan.close();
}
}
|
cs |
하면서 배운 점!
1. printf와 println의 차이점
println은 변수나 입력한 내용을 그대로 출력할 때 사용되고,
printf는 서식을 지정할 때 사용된다.
println은 System.out.println("참가자의 이름을 입력하세요.")와 같이 그대로 출력해 주고 싶을 때 사용하고,
서식을 지정할 때는 System.out.printf("%d", a[i])와 같이 반드시 printf를 써 주어야 한다!
2. 한 class 파일 내에서 두 개의 클래스를 선언할 때
파일을 A 클래스로 형성했다면 public class 선언은 A 클래스에서만 사용할 수 있다.
만약 A 이름의 클래스 파일 내에서 B 클래스에 public을 붙이게 되면 다음과 같은 오류가 뜬다.
"The public type B must be defined in its own file"
'개발공부' 카테고리의 다른 글
[Python] 다른 사람 마음읽기 알고리즘 (0) | 2020.07.13 |
---|---|
[Python] '파티에 참석하기 가장 좋은 시간' 알고리즘 연습문제 (0) | 2020.07.02 |
[Python] '파티에 참석하기 가장 좋은 시간' 알고리즘 (1) | 2020.07.01 |
[Python] 모두 똑같이 만들기 알고리즘 연습문제 (2) | 2020.07.01 |
[Python] '모두 똑같이 만들기' 알고리즘 (1) | 2020.07.01 |