String s = i+"";
를 사용하면 좋다.
숫자야구 게임을 자바화시켰다.
// 1. 메인 클래스
package chap08;
public class ArrBaseballEx {
public static void main(String[] args) {
int[] comArr = new int[3];
int[] userArr = new int[3];
int count = 0;
ArrBaseballLib abl = new ArrBaseballLib();
abl.makeEachInt(comArr);
while(true) {
count++;
userArr = abl.toArray();
int[] arr = abl.compareArr(comArr, userArr);
int strike = arr[0];
int ball = arr[1];
int out = arr[2];
System.out.printf("숫자 '%s%s%s' - Strike:%s, Ball:%s, Out:%s (시도횟수:%s)\n",userArr[0],userArr[1],userArr[2],strike,ball,out,count);
if(strike==3) {
System.out.println("게임에서 이겼습니다!");
break;
}
}
}
}
// 2. 숫자야구 메서드 구현
package chap08;
import java.util.Scanner;
public class ArrBaseballLib {
Scanner scan = new Scanner(System.in);
//컴퓨터가 생성한 세자리 인트값 검수
public void makeEachInt(int[] a) {
while(true) {
for(int i=0; i<a.length; i++) {
a[i] = (int)(Math.random()*9+1);
}
boolean b = true;
for(int i=0; i<a.length; i++) {
for(int j=0; j<a.length; j++) {
if(i != j) {
if(a[i] == a[j]) {
b = false;
}
}
}
}
if(b){
break;
}
}
}
//사람이 입력한 세자리 숫자 검수, 배열화
public int[] toArray() {
int[] copyArr = new int[3];
System.out.println("세자리 숫자를 입력하세요.");
while(true) {
String s = scan.next();
copyArr[0] = s.charAt(0)-'0';
copyArr[1] = s.charAt(1)-'0';
copyArr[2] = s.charAt(2)-'0';
boolean b = true;
reset:
for(int i=0; i<copyArr.length; i++) {
for(int j=0; j<copyArr.length; j++) {
if(i != j) {
if(copyArr[i] == copyArr[j]) {
System.out.println("겹치지 않는 숫자를 입력하세요.");
b = false;
break reset;
}
}
}
if(copyArr[i] == 0) {
System.out.println("0을 제외하고 입력하세요.");
b = false;
break reset;
}
}
if(b){
break;
}
}
return copyArr;
}
//컴퓨터와 사람의 배열 비교
public int[] compareArr(int[] a, int[] b) {
int strike = 0;
int ball = 0;
int out = 0;
if(a[0]==b[0]) {
strike++;
} else if (a[0]==b[1] || a[0]==b[2]) {
ball++;
} else {
out++;
}
if(a[1]==b[1]) {
strike++;
} else if (a[1]==b[0] || a[1]==b[2]) {
ball++;
} else {
out++;
}
if(a[2]==b[2]) {
strike++;
} else if (a[2]==b[0] || a[2]==b[1]) {
ball++;
} else {
out++;
}
int[] arr = new int[3];
arr[0] = strike;
arr[1] = ball;
arr[2] = out;
return arr;
}
}