I have been making a basic game of battleship and to get the CPU to choose ship locations on a 2d array I am making two random number generators to pick values from 1 to 8 on a separate method. For some reason, the random generators show up as unused and I don’t know why. so far this is what I have. If anyone knows what I’m doing wrong please let me know.
//calls method board3 = CPUship(board3); //displays result of method for (int i = 0; i < board3.length; i++) { for (int j = 0; j < board3.length; j++) { System.out.print(board3[i][j]); } System.out.println(""); }
public static String[][] CPUship(String[][] board3) { int rowGenerate; int colGenerate; boolean valid2 = false; for (int CPUships = 0; CPUships < 6; CPUships++) { while (!valid2) { rowGenerate = (int) (9 * Math.random() + 0); colGenerate = (int) (9 * Math.random() + 0); if (!board3[rowGenerate][colGenerate].equalsIgnoreCase("#")) { board3[rowGenerate][colGenerate] = "#"; valid2 = true; } } valid2 = false; } return board3; }
Advertisement
Answer
Here should be a complete code
public static String[][] CPUship(String[][]board3){ int rowGenerate; int colGenerate; for (int CPUships = 0; CPUships < 6; CPUships++) { boolean valid2=false; while (!valid2){ //instead of valid = false " rowGenerate = (int) ( 9* Math.random() + 0); colGenerate = (int) ( 9* Math.random() + 0); if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){ board3[rowGenerate][colGenerate]="#"; valid2=true; } //removed the valid2=false, it does not "reset" automatically //removed the CPUships++ ... already done by the for loop } } return board3; }
or use break instead of the valid boolean
public static String[][] CPUship(String[][]board3){ int rowGenerate; int colGenerate; for (int CPUships = 0; CPUships < 6; CPUships++) { while (true){ //instead of valid = false " rowGenerate = (int) ( 9* Math.random() + 0); colGenerate = (int) ( 9* Math.random() + 0); if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){ board3[rowGenerate][colGenerate]="#"; break; } //removed the valid2=false, it does not "reset" automatically //removed the CPUships++ ... already done by the for loop } } return board3; }