java - Why does my program print out the exception statement endlessly give bad user input? -


ive no idea if title made sense here code ©

import java.util.inputmismatchexception; import java.util.scanner; public class gussing {     public static void thegame(scanner input){         int randomnum= (int)(math.random()*101);//randomizes number between 0-100 inclusive of both         system.out.println(randomnum); //for debugging purposes         int attemptcounter = 0; //counts how many attempts user make         system.out.print("welcome guess-the number game! enter guess: ");          while(true){             system.out.println("here bad input");             try{                 system.out.println("here after bad input");                 int userinput= input.nextint();                 if (userinput==randomnum) //when usr input , generated random number equal print how many attempts                 {                     attemptcounter++;                     system.out.println("congrats made right guess after "+ attemptcounter + " attempts!");                     break;                  }                  if(userinput<randomnum){                     attemptcounter++;                     system.out.print("too low! try again: ");                      }                 else {                     attemptcounter++; //else clause opposite of if clause                     system.out.print("too high! try again: ");                      }                   }             catch( exception e){                     system.out.println("invalid input");                      }             }      }     public static void main(string[] args){         scanner input = new scanner (system.in);         thegame (input);           system.out.println("play again? (y/n)");          try{             char answer=input.next().tolowercase().charat(0);                //tolowercase method n =n = no !              if (answer =='y') thegame (input);               else if (answer =='n') system.out.println("good bye");               input.close(); //no more input data              }         catch(exception e){             system.out.println("invalid input");         }     }   } 

so when user types in wrong type i.e not int prints out invalid input. not problem problem prints out infinitely. tried adjusting try catchblocks didnt @

nextint doesnt remove non-integer data input buffer gets recycled indefinitely unless data consumed. in case inputmismatchexception thrown method write exception block

} catch (inputmismatchexception e) {     system.out.println("invalid input " + input.nextline()); } 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -