Follow the examples in the book.
However, the bug mentioned in the book, I did not look at the next chapter when the resolution of Kazakhstan.
The method of removing an array element from the Web lookup.
In fact, changing the data structure to ArrayList may be easier. :)
Gamehelper.java
ImportJava.io.*; Public classGamehelper { Publicstring Getuserinput (String prompt) {string Inputline=NULL; System.out.println (Prompt+ " "); Try{BufferedReader is=NewBufferedReader (NewInputStreamReader (system.in)); Inputline=Is.readline (); if(inputline.length () = = 0 ) return NULL; } Catch(IOException e) {System.out.println ("IOException:" +e); } returnInputline; }}
Simpledotcom.java
Public classsimpledotcom {int[] locationcells; intNumofhits = 0; Public voidSetlocationcells (int[] locs) {Locationcells=locs; } Public int[] Dellocationcells (inteleint) { for(inti = 0; i < locationcells.length; i++) { if(Eleint = =Locationcells[i]) { for(intj = i + 1; J < Locationcells.length; J + +) {Locationcells[i]=Locationcells[j]; } } } returnLocationcells; } Publicstring Checkyourself (String stringguess) {intGuess =Integer.parseint (stringguess); String result= "Miss"; for(intcell:locationcells) { if(Guess = =cell) {Result= "Hit"; Numofhits++; Dellocationcells (guess); Break; } } if(Numofhits = =locationcells.length) {result= "Kill"; } System.out.println (Result); returnresult; }}
Simpledotcomtestdrive.java
Public classsimpledotcomtestdrive { Public Static voidMain (string[] args) {intnumofguesses = 0; Gamehelper Helper=NewGamehelper (); Simpledotcom thedotcom=Newsimpledotcom (); intRandomnum = (int) (Math.random () * 5); int[] locations = {Randomnum, Randomnum + 1, Randomnum + 2}; Thedotcom.setlocationcells (locations); BooleanIsAlive =true; while(IsAlive = =true) {String guess= Helper. Getuserinput ("Enter A number"); String result=thedotcom.checkyourself (guess); Numofguesses++; if(Result.equals ("Kill") ) {isAlive=false; System.out.println ("You took" + numofguesses + "guesses."); } } }}
Output:
Simple guess Numbers (Java edition)