2017/08/05

猜數字遊戲(Java)

import java.util.Scanner;

public class GuessNumber {

static Scanner scn = new Scanner(System.in);

public static void main(String[] args) {
int digit = 4;
guessRand(getRandom(digit));
scn.close();
}

public static String getRandom(int digit) {
String stringRandom = "";

for (int i = 1; i <= digit; i++) {
int randomNumber = ((int) (Math.random() * 10));
if (((stringRandom.length() == 0) && (randomNumber != 0))
|| ((stringRandom.length() > 0) && (stringRandom.indexOf(String.valueOf(randomNumber)) == -1))) {
stringRandom = stringRandom + randomNumber;
} else {
i--;
}
}

return stringRandom;
}

public static void guessRand(String randomNumber) {
int A = 0, B = 0;
String userNumber = "";

while (!randomNumber.equals(userNumber)) {
System.out.printf("請輸入%d位數的數字:", randomNumber.length());
userNumber = scn.next();
for (int i = 0; i < randomNumber.length(); i++) {
if (randomNumber.charAt(i) == userNumber.charAt(i))
A++;
else if (randomNumber.indexOf(userNumber.charAt(i)) != -1)
B++;
}
System.out.printf("%dA%dB\n", A, B);
A = 0;
B = 0;
}
System.out.printf("恭喜你答對了,正確數字是" + userNumber);
}
}