Em đang học lập trình Java trong sách HeadFirst và có đoạn này em chưa hiểu kĩ
Vì 3 class khá dài nên em chỉ post đoạn cần hỏi là class GameHelper:
public class GameHelper {
private static final String alphabet = "abcdefg";
private int gridLength = 7;
private int gridSize = 49;
private int[] grid = new int[gridSize];
private int comCount = 0;
public ArrayList<String> placeDotCom(int comSize) {
ArrayList<String> alphaCells = new ArrayList<String>();
String[] alphacoords = new String[comSize];
String temp = null;
int[] coords = new int[comSize];
int attempts = 0;
boolean success = false;
int location = 0;
comCount++;
int incr = 1;
if ((comCount % 2) == 1) {
incr = gridLength;
}
while (!success & attempts++ < 200) {
location = (int) (Math.random() * gridSize);
System.out.println("try " + location);
int x = 0;
success = true;
while (success && x < comSize) {
if (grid[location] == 0) {
coords[x++] = location;
location += incr;
if (location >= gridSize) {
success = false;
}
if (x > 0 && (location % gridLength == 0)) {
success = false;
}
} else {
System.out.println(" used " + location);
success = false;
}
}
}
int x = 0;
int row = 0;
int column = 0;
System.out.println("\n");
while (x < comSize) {
grid[coords[x]] = 1;
row = (int) (coords[x] / gridLength);
column = coords[x] % gridLength;
temp = String.valueOf(alphabet.charAt(column));
alphaCells.add(temp.concat(Integer.toString(row)));
System.out.println(coords[x]);
x++;
System.out.println("coord "+x+"= "+ alphaCells.get(x-1));
}
return alphaCells;
}
Chương trình sẽ tạo ra một khối 7x7 với số cột là A đến G và số hàng là từ 0 đến 6 và tạo một chiếc thuyền có 3 khối lần lượt theo thứ tự là dọc,ngang và dọc
nhưng khi e chạy chương trình thì vị trí 11 tăng ngang sẽ là 11,12,13 tương ứng E1,F1,G1 lại bị skip và không được tính
hoặc khi vị trí 6 tương ứng tăng dần là 6,13,20 thì chương trình cũng skip
Mọi người cho em hỏi bug này phải sửa thế nào ạ??
Và tại sao lại có bug này?




83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?