Jose Vidal shared this file. Want to do more with it?
importjava.util.Scanner;
/**
*Main.java
*A simple game of guess the number.
*@authorJoseMVidal<jmvidal@gmail.com>
*Created on Jan19,2012
*
*/
publicclassMain{
publicstaticvoidmain(String[] args){
finalint secretLength =4;//the number of digits in the secret. I can change this later if I want to make it harder
Scanner keyboard =newScanner(System.in);
System.out.println("Guess the "+ secretLength +"-digit number I am thinking of.");
boolean done =false;
int secretInteger =(int)(Math.random()*10000);
String secret =Integer.toString(secretInteger);
while(secret.length()< secretLength){//append 0's at the left of the number until it is of length 4
secret ="0"+ secret;
}
System.out.println("(the secret is "+ secret +")");
while(! done){
System.out.print("Your guess:");
String guess = keyboard.next();//Treating it like a string, not an int.
if(guess.length()== secretLength){
int numCorrectDigits =0;//the number of digits in correct position
int numDigitsNotInSecret =0;//the number of digits in guess that are nowhere in secret
for(int index =0; index < secretLength; index++){
if(guess.charAt(index)== secret.charAt(index))//at the correct position
numCorrectDigits++;
if(! secret.contains(guess.substring(index,index+1))){//this digit is NOT in secret
numDigitsNotInSecret++;
}
}
System.out.println(guess +" has "+ numCorrectDigits +" digits in the correct position.");
System.out.println(guess +" has "+ numDigitsNotInSecret +" digits that are not found anywhere in the secret number.");
if(numCorrectDigits == secretLength)
done =true;
}
else{
System.out.println("Enter only a "+ secretLength +"-digit number");
}
}
System.out.println("Congratulations! You guessed correctly.");
}
}
We use cookies to provide, improve, protect and promote our services. Visit our Privacy Policy and Privacy Policy FAQs to learn more. You can manage your personal preferences, including your ‘Do not sell or share my personal data to third parties’ setting using the “Customize cookies” button below.