2017-02-23 26 views
-1

Я имею проблему, делая экземпляр моего стека в классе GameController.java:Определение ссылочной переменной стека

import java.awt.*; 

public class GameController implements ActionListener { 

private GameModel model; 
private MyStack<DotInfo[][]> dots; 
private int size; 

/** 
* Constructor used for initializing the controller. It creates the game's view 
* and the game's model instances 
* 
* @param size 
*   the size of the board on which the game will be played 
*/ 
public GameController(int size) { 
    this.size = size; 
    model = new GameModel(size); 
    dots = (MyStack<DotInfo[][]>) new DotInfo[size][size]; 
} 

/** 
* resets the game 
*/ 
public void reset(){ 
    model.reset(); 
} 

/** 
* Callback used when the user clicks a button (reset or quit) 
* 
* @param e 
*   the ActionEvent 
*/ 

public void actionPerformed(ActionEvent e) { 

} 

/** 
* <b>selectColor</b> is the method called when the user selects a new color. 
* If that color is not the currently selected one, then it applies the logic 
* of the game to capture possible locations. It then checks if the game 
* is finished, and if so, congratulates the player, showing the number of 
* moves, and gives two options: start a new game, or exit 
* @param color 
*   the newly selected color 
*/ 
public void selectColor(int color){ 
    Stack<DotInfo[][]> newStack = new DotInfo[size][size]; 
    for (int i=0;i<size;i++) { 
     for (int j=0;j<size;j++) { 
      if (model.dots[i][j].isCaptured()) { 
       dots.push(dots[i][j]); 
      } 
     } 
    } 
    while (model.getCurrentSelectedColor()!=color) { 
     color=model.setCurrentSelectedColor(color); 
     //for (int i=0;i<) 
    } 
} 
} 

Это мой Stack.java класс:

public class MyStack<T> implements Stack<T> { 

private T[][] array; 
private int size; 

public MyStack(int size) { 
    this.size = size; 
    array = (T[][])new Object[size][size]; 
} 

public boolean isEmpty() { 
    return size==0; 
} 

public T peek() { 
    return array[size][size]; 
} 

public T pop() { 
    T popped = null; 
    popped = array[size][size]; 
    size--; 
    return popped; 
} 

public void push(T element) { 
    size++; 
    array[size][size]=element; 
} 
} 

I также задавался вопросом, правильно ли я определил класс стека? Небольшая помощь будет оценена.

+0

ли компилировать код? Поскольку 'dots' определяется как Stack, где каждый элемент является двумерным массивом объектов DotInfo, ваша инициализация' dots' в конструкторе должна быть чем-то вроде 'dots = new MyStack <>();' в Java 8 и 'dots = new MyStack ();' в более старых реализациях Java. –

ответ

0

Стек не работает должным образом, потому что вам необходимо установить внутреннее поле позиции в конструктор, а не аргумент size.

Также [размер] [размер] бесполезно, его всегда диагонали в ваших сложенных объектов, просто использовать [размер] (1 мерный массив) для стека, ниже рабочий стек типа Т:

public class MyStack<T> implements Stack<T> { 

private Object[] array; 
private int size, int position; 

public MyStack(int size) { 
    this.size = size; 
    position = 0; 
    array = new Object[size]; 
} 

public boolean isEmpty() { 
    return position < 1; 
} 

public T peek() { 
    if (isEmpty()) 
     throw new RuntimeException("Stack is empty"); 

    return (T)array[position]; 
} 

public T pop() { 
    if (isEmpty()) 
     throw new RuntimeException("Stack is empty"); 

    return array[position--]; 
} 

public void push(T element) { 
    if (position >= size - 1) 
     throw new RuntimeException("Stack is full"); 

    array[++position]=element; 
} 

} 

Кроме того, для настольной игры вы делаете, почему используют стек вообще, просто использовать 2 одномерный массив как:

public class Dot { 
    //whatever information you need about a dot here 

    //As example just say Hello 
    public void sayHello() { 
     System.out.println("Hello"); 
    } 
} 

и использовать его в качестве 2D-массив:

//this are chess board dimensions (8 x 8) 
public static final int SIZE_X = 8; 
public static final int SIZE_Y = 8; 

//create the board, made of Dot instances 
Dot[][] board = new Dot[SIZE_X][SIZE_Y]; 

Чтобы найти и использовать данный Dot:

//get reference of dot at position x, y 
Dot dot = board[x][y]; 

//check if it exists, and if it does, make it sayHello() 
if (dot != null) { 
    dot.sayHello(); 
} 
+0

Мне нужно использовать массив стека для назначения –

+0

Как бы инициализировать мой стек в моем классе GameController.java –

+0

просто используйте stackArr = new MyStack [size]; – CrowsNet