java - How to track the total number of attempts made by the user to input data -
i have made simple guessing game. want count sum of attempts user made before finding original number. means once hidden number matched user input, should tell how many numbers has been entered before user won.
this code:
package guessinggame; import java.util.scanner; public class guessinggame { public static void main(string[] args) { int hiddennum = 10; scanner input = new scanner(system.in); while (true) { system.out.println("enter numebr guessing: "); int guessednum = input.nextint(); if (guessednum == hiddennum) { system.out.println("congratulation! number matched"); system.exit(0); } else if (guessednum < hiddennum) { system.out.println("not matched! try bigger number"); } else if (guessednum > hiddennum) { system.out.println("not matched! try smaller number"); } } } }
simply use counter counter number of guesses:
package guessinggame; import java.util.scanner; public class guessinggame { public static void main(string[] args) { //storing hidden number in variable int hiddennum = 10; //introducing scanner class (for user input) scanner input = new scanner(system.in); //asking user enter random number //counter counter number of guesses int numofguesses = 0; while (true) { system.out.println("enter numebr guessing: "); //storing variable int guessednum = input.nextint(); numofguesses++; //increment number of guesses //checking wheather number matched if (guessednum == hiddennum) { system.out.println("congratulation! number matched"); system.out.println("you have made " + numofguesses + " attempts find number!"); //if matched number found, terminate program system.exit(0); //checking condition } else if (guessednum < hiddennum) { system.out.println("not matched! try bigger number"); //checking condition } else if (guessednum > hiddennum) { system.out.println("not matched! try smaller number"); } } } }
Comments
Post a Comment