Thursday 15 July 2010

java - HiLo Game With Random Number Generator -



java - HiLo Game With Random Number Generator -

i have 1 real quick question hilo game. when go , test works except when want display how many tries took them guess. i'm trying doesn't count initial guess, counts ones after shows 1 less guess is. here code.

edit:i have quick question. want programme not count guess if out of range 0 10. how go doing because when run programme counts guess 1 of tries.

class="snippet-code-js lang-js prettyprint-override">import java.util.random; // random number generator class import java.util.scanner; // reads user inputs public class hilo { public static void main (string[] args) { //declare variables final int max = 10; int answer, guess; int numberoftries = 0 ; string again; scanner keyboard = new scanner(system.in); do { system.out.print (" i'm thinking of number between 0 , " + max + ". guess is: "); guess = keyboard.nextint(); //guess random generator = new random(); //random number generator. 0 10. answer = generator.nextint(max) +1; if (guess > 10)//if guess bigger 10 error message { system.out.println ("error – guess out of range 0 10."); } if (guess < 0)//if guess smaller 0 error message { system.out.println ("error – guess out of range 0 10."); } while (guess != reply )//if guess not reply { if (guess > reply )//if guess more reply { system.out.println ("you guessed high! \ntry again:"); guess = keyboard.nextint(); } if (guess < reply )//if guess less reply { system.out.println ("too low! \ntry again:"); guess = keyboard.nextint(); } numberoftries=numberoftries+1; }//end of loop // display result if ( guess == answer) { numberoftries += 1; system.out.println ("you win!"); system.out.println("it took " + numberoftries + " tries!") ; system.out.println(); system.out.print( "do want play again(y/n)?"); } keyboard.nextline(); // skip on come in key again = keyboard.nextline(); numberoftries=0; }while (again.equalsignorecase ("y") ); } // end of class } //end of main

thank you!

you should set numberoftries += 1 within if ( guess == reply ), way counts right reply well

if ( guess == answer) { numberoftries += 1; // <--- adds final guess system.out.println ("you win!"); system.out.println("it took " + numberoftries + " tries!") ; system.out.println(); system.out.print( "do want play again(y/n)?"); }

java

No comments:

Post a Comment