На самом деле нет оснований для использования ArrayList. Для моей школы, я пишу экзамен, именно по этой теме и У меня только немного кода, который отлично работает, и я просто отправлю его здесь для вас и объясню.
public class Feld implements Cloneable{
private int value; //0 = kein Stein 1 = Team weiß 2 = Team schwarz (0 by default)
public Feld() {
}
public Feld(int v) {
this.setValue(v);
}
public int getValue() {
return value;
}
public void negate(){
value = -value;
}
public void setValueWithoutRangeCheck(int value){
this.value = value;
}
public void setValue(int value) {
if(inrange(value))
this.value = value;
}
private boolean inrange(int value) {
return (value >= -1 && value <= 1);
}
public Feld clone() {
return new Feld(value);
}
@Override
public String toString() {
return "Feld{" + "value=" + value + '}';
}
}
Это мой полевой класс (немецкий «Feld»). Вы должны просто переименовать его. Каждое поле получило значение. inrange проверяет, имеет ли значение -1,0,1 (может использоваться для teamA, ничего, teamB (например). Отрицание просто изменяет значение поля (например, от 1 до -1). Если вы собираетесь создать KI, вам нужно клонировать этот объект (если вы хотите знать, как писать KI в TIC TAC TOE, я могу вам это объяснить (просто отправьте мне письмо по электронной почте [email protected])
My Seccond класс моего actuall массив:.
public class FeldArray implements Cloneable{
private Feld[][] felder;
public class FeldArrayIterator{
private FeldArray array;
private int currentX;
private int currentY;
protected FeldArrayIterator(FeldArray array,int x, int y){
this.array = array;
this.currentX = x;
this.currentY = y;
}
public void goTo(int x, int y){
this.currentX = x;
this.currentY = y;
}
public void next(int x, int y) {
this.currentX = this.currentX + x;
this.currentY = this.currentY + y;
}
public int getCurrentX() {
return this.currentX;
}
public int getCurrentY() {
return this.currentY;
}
public void next() {
this.currentX ++;
if(this.getCurrent() == null){
this.currentX = 0;
this.currentY ++;
}
}
public Feld getCurrent() {
return array.getFeld(currentX, currentY);
}
}
public FeldArrayIterator iterator() {
return new FeldArrayIterator(this,0,0);
}
public FeldArray(int size){
this.resetFeld(size);
}
public int getAmountOf(int i){
int lsg = 0;
FeldArrayIterator it = this.iterator();
while(it.getCurrent() != null){
if(it.getCurrent().getValue() == i){
lsg ++;
}
it.next();
}
return lsg;
}
public int getSize() {
return this.felder.length;
}
private void resetFeld(int size) {
felder = new Feld[size][size];
for(int i = 0; i < this.getSize(); i++){
for(int n = 0; n < this.getSize(); n++){
this.setFeld(new Feld(), i, n);
}
}
}
private Feld getFeld(int x, int y) {
if(inrange(x,y))
return this.felder[x][y];
else{
return null;
}
}
private void setFeld(Feld f, int x, int y){
if(inrange(x,y))
this.felder[x][y] = f;
}
public void setValue(int value,int x, int y){
if(inrange(x,y))
this.getFeld(x, y).setValue(value);
}
public int getValue(int x, int y) {
if(inrange(x,y)){
return this.getFeld(x, y).getValue();
}
else{
return 0;
}
}
public FeldArray clone() {
FeldArray array = new FeldArray(this.getSize());
for(int i = 0; i < this.getSize(); i++){
for(int n = 0; n < this.getSize(); n++){
array.setFeld(this.getFeld(i, n).clone(), i, n);
}
}
return array;
}
public String toString() {
String res = "FeldArray\n";
for(int i = 0; i < this.getSize(); i++){
for(int n = 0; n < this.getSize(); n++){
res += this.getValue(n,i)+" ";
}
res += "\n";
}
res += "-----------------";
return res;
}
private boolean inrange(int x, int y) {
return (x >= 0 && y >= 0 && x < this.getSize() && y < this.getSize());
}
}
Это на просто создает массив, его невозможно получить любое значение за пределами массива Так что не может быть выброшены какими-либо исключения)
Также я реализовал итератор.Если вы не знаете, что это такое, я просто объясню это:
Вы можете создать новый итератор, вызвав: youArray.iterator(). Это возвращает новый Iterator из типа FeldArrayIterator Этот Iterator имеет поле и, вызывая getCurrent(), вы получаете элемент actall массива, на который указывает итератор. Вызов next(). Он переходит к следующему элементу массива. Так что, когда вы хотите получить каждый элемент массива нужно просто позвонить:
FeldArrayIterator it = array.iterator();
while(it.getCurrent() != null) {
//doSomething
it.next();
}
На самом деле его бросить легко. но никогда не забывайте его .next().
Позвонив по адресу.next (x, y). Вы можете перейти к любому элементу, относящемуся к вашей позиции. Итак, если ваше текущее положение (1,2) и вы говорите it.next (2,2). Ваша текущая позиция (3,4).
Надеюсь, я мог бы помочь вам в этом.
Добро пожаловать в stackoverflow! Было бы полезно, если бы вы добавили пример ввода для тестирования своей программы. – TobiMarg
Вы проверили размер своего списка после того, как закончите его заполнение? Все ли значения индекса вызывают исключение или только конкретное? – Frank