java - Guessing game adding a method -



java - Guessing game adding a method -

i need add together method guessing game made while ago. method should homecoming value come in should utilize loop require re-entry until 1 of 2 values has been specified. if user inputs word , not int, should inquire number. know need utilize string instead of int. i'm having problem figuring out. here have far:

import java.util.random; import java.util.scanner; class guessnumber { static random rand = new random(); static scanner scan = new scanner(system.in); static int number; public static void main(string[] args) { playgame(); } public static void playgame() { number = rand.nextint(100) + 1; system.out.println("guess number between 1 , 100"); while (true) { int guess = scan.nextint(); if (guess < number) { system.out.println("higher!"); } else if (guess > number) { system.out.println("lower!"); } else if (guess == number) { system.out.println("correct!"); scanner scan2 = new scanner(system.in); system.out.println("do wanna play again?[y/n]"); string val = scan2.next(); if (val.equalsignorecase("y")) { playgame(); } else { break; } } } } }

there might improve way seek along lines of:

string input = scan.next(); int guess; try{ guess = integer.parseint(input); //rest of code within while(true) loop } catch(exception e){ system.out.println("you need come in valid number."); }

and y/n validation:

string val = "no"; scanner scan2 = new scanner(system.in); do{ system.out.println("do wanna play again?[y/n]"); val = scan2.next(); } while(!val.equalsignorecase("y") && !val.equalsignorecase("n")) if (val.equalsignorecase("y")) { playgame(); break; } else { break; }

reasoning: error if not come in valid number need grab error , allow them know wrong. input string , seek convert integers. do/while section... unless come in y or n maintain asking them. 1 time out of loop, if input "y" phone call playgame() 1 time again , break after finishes (basically whenever user types n in next game). if wasn't "y" had "n" , needs break.

let me know if helps. have total code work should easy plenty implement.

java methods jgrasp

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -