1. import java.util.Scanner;
  2. 
  3. /**
  4. * Main.java
  5. * A simple game of guess the number.
  6. * @author Jose M Vidal <jmvidal@gmail.com>
  7. * Created on Jan 19, 2012
  8. *
  9. */
  10. public class Main {
  11. 
  12. public static void main(String[] args) {
  13. final int secretLength = 4; //the number of digits in the secret. I can change this later if I want to make it harder
  14. Scanner keyboard = new Scanner(System.in);
  15. System.out.println("Guess the " + secretLength + "-digit number I am thinking of.");
  16. boolean done = false;
  17. int secretInteger = (int)(Math.random() * 10000);
  18. String secret = Integer.toString(secretInteger);
  19. while (secret.length() < secretLength) { //append 0's at the left of the number until it is of length 4
  20. secret = "0" + secret;
  21. }
  22. System.out.println("(the secret is " + secret + ")");
  23. while (! done){
  24. System.out.print("Your guess:");
  25. String guess = keyboard.next(); //Treating it like a string, not an int.
  26. if (guess.length() == secretLength) {
  27. int numCorrectDigits = 0; //the number of digits in correct position
  28. int numDigitsNotInSecret = 0; //the number of digits in guess that are nowhere in secret
  29. for (int index = 0; index < secretLength; index++){
  30. if (guess.charAt(index) == secret.charAt(index)) //at the correct position
  31. numCorrectDigits++;
  32. if (! secret.contains(guess.substring(index,index+1))){ //this digit is NOT in secret
  33. numDigitsNotInSecret++;
  34. }
  35. }
  36. System.out.println(guess + " has " + numCorrectDigits + " digits in the correct position.");
  37. System.out.println(guess + " has " + numDigitsNotInSecret + " digits that are not found anywhere in the secret number.");
  38. if (numCorrectDigits == secretLength)
  39. done = true;
  40. }
  41. else {
  42. System.out.println("Enter only a " + secretLength + "-digit number");
  43. }
  44. }
  45. System.out.println("Congratulations! You guessed correctly.");
  46. }
  47. 
  48. }