I want to create game tic-tac-toe. I use the List class to determine a winner. I use List in several methods. How do I create this class in main method so that I can use List other method later?
I have attached my code so that you understand my question.
public class Main {
public static void main(String[] args) {
List<Integer> playerPositions = new ArrayList<>(); //создадим список для определения победителя
List<Integer> CPUpositions = new ArrayList<>();
//создать двумерный массив для отрисовки игры
char[][] gameBoard = new char[][] {
{ ' ', '|', ' ', '|', ' '},
{ '-', ' ', '-', ' ', '-'},
{ ' ', '|', ' ', '|', ' '},
{ '-', ' ', '-', ' ', '-'},
{ ' ', '|', ' ', '|', ' '}
};
// printGameBoard(gameBoard);
}
public static String checkWinner() {
List toprow = Arrays.asList(1, 2, 3);
List midrow = Arrays.asList(4, 5, 6);
List botrow = Arrays.asList(7, 8, 9);
List col1 = Arrays.asList(1, 4, 7);
List col2 = Arrays.asList(2, 5, 8);
List col3 = Arrays.asList(3, 6, 9);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(3, 5, 7);
return "";
}
}
CodePudding user response:
You create your ArrayList within the main method. Therefore you cannot access those variables outside of the main method. You should declare them as private class variables like this:
public class Main {
List<Integer> playerPositions = new ArrayList<>();
List<Integer> CPUpositions = new ArrayList<>();
public static void main(String[] args) {
// Do sth with playerPositions and CPUpositions
}
CodePudding user response:
Create a static List of List.
List called winningList and check if playerPositions contains any of the List in winningList or CPUpositions contains any of the list part of winningList.
Whichever has the list has won.
CodePudding user response:
There's multiple ways to go about this:
a) create playerPositions and CPUpositions as static class variables - basically what user dcnis said, except you'll need to add the "static" keyword to be able to use them without instanciating a "Main" object:
public class Main {
static List<Integer> playerPositions = new ArrayList<>();
static List<Integer> CPUpositions = new ArrayList<>();
public static void main(String[] args) {
// Do sth with playerPositions and CPUpositions
}
Alternatively, you can pass the lists down to your functions as an argument:
public static void main(String[] args){
List<Integer> playerPositions = new ArrayList<>();
List<Integer> CPUPositions = new ArrayList<>();
checkWinner(playerPositions, CPUPositions);
}
public static void checkWinner(List<Integer> playerPositions, List<Integer> CPUPositions){
//do cool stuff with those lists
}
