1. 소개
제가 만든 숫자야구 게임입니다.
2. 소스
import java.util.Scanner;
public class NumberBaseball {
int digit = 4;
int count = 0;
String result = "";
public static void main(String[] args) {
NumberBaseball nb = new NumberBaseball();
nb.init();
nb.match();
}
void init() {
while (result.length() < digit) {
String random = (int) (Math.random() * 10) + "";
if (result.contains(random)) {
continue;
} else {
result += random;
}
}
}
void match() {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
String yourNumber = null;
while (true) {
System.out.print("yourNumber=");
yourNumber = scanner.nextLine();
int strike = 0;
int ball = 0;
if (yourNumber.length() != digit) {
System.out.println("Please input " + digit + " digit number ... ");
} else {
for (int inx = 0; inx < yourNumber.length(); inx++) {
String c = yourNumber.charAt(inx) + "";
if (result.contains(c)) {
if (result.indexOf(c) == inx)
strike++;
else
ball++;
}
}
if ( strike == 4 ) {
System.out.println("You win! Game over!");
System.exit(0);
} else if (strike > 0 || ball > 0) {
System.out.println(strike + " Strike " + ball + " Ball!");
} else {
System.out.println("Out!");
}
}
}
} catch (Exception e) {
//
} finally {
scanner.close();
}
}
}
