Skip to content

Instantly share code, notes, and snippets.

Created October 20, 2012 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3924199 to your computer and use it in GitHub Desktop.
Save anonymous/3924199 to your computer and use it in GitHub Desktop.
Number guessing game
for(Object o : new Iterable<Object>(){
public Iterator<Object> iterator() {
return new Iterator<Object>(){
private static final int MAX_NUMBER = 100;
private static final int MIN_NUMBER = 1;
private Random r = new Random();
private int number;
private int guess;
{
number = r.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
System.out.printf("guess a number between %d and %d (inclusive).%n",MIN_NUMBER,MAX_NUMBER);
}
private Scanner in = new Scanner(System.in);
public boolean hasNext() {
System.out.print("> ");
guess = in.nextInt();
if(guess == number){
System.out.printf("You win! %d was the right number!%n",number);
return false;
}
System.out.printf("The number is %s than %d%n", number > guess ? "larger" : "smaller",guess);
return true;
}
public Object next() {
return null;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment