java - Issue converting array to array list -
trying write java code single row battleship style game, , when tried convert array arraylist, game started returning "miss" no matter what.
public class simpledotcomgame { public static void main(string[] args) { int numofguess = 0; scanner sc = new scanner(system.in); simpledotcom dot = new simpledotcom(); int rannum = (int) (math.random() * 5); arraylist<integer> locations = new arraylist<integer>(); locations.add(rannum); locations.add(rannum + 1); locations.add(rannum + 2); dot.setlocationcells(locations); //think you're running // separate program parameters set cells "locations" boolean isalive = true; while (isalive == true) { system.out.println("enter number"); string userguess = sc.next(); string result = dot.checkyourself(userguess); //run program // check if cells hit userguess numofguess++; if (result.equals("kill")) { isalive = false; system.out.println("you took " + numofguess + " guesses"); } } sc.close(); } }
public class simpledotcom { int numofhits = 0; arraylist<integer> locationcells; public void setlocationcells(arraylist<integer> locations) { //locations // variable described array must define array locationcells = locations; } public string checkyourself(string userguess) { //check using parameter userguess int guess = integer.parseint(userguess); string result = "miss"; int index = locationcells.indexof(userguess); if (index >= 0) { locationcells.remove(index); if (locationcells.isempty()) { result = "kill"; } else { result = "hit"; } } system.out.println(result); return result; } }
change :
int index = locationcells.indexof(userguess);
to
int index = locationcells.indexof(guess);
userguess string can not possibly in list of integers. guess int can.
Comments
Post a Comment