I created a tic-tac-toe using java and I would like to know if there are any practices that I can improve and make the code cleaner and more performative
import java.util.Scanner;
public class Main {
public static boolean test(String[] values){
//Check diagonals
if((values[0].equals("X") && values[4].equals("X") && values[8].equals("X")) || (values[0].equals("0") && values[4].equals("0") && values[8].equals("0"))){
System.out.print(values[0] + " win");
return true;
}
if((values[2].equals("X") && values[4].equals("X") && values[6].equals("X")) || (values[2].equals("0") && values[4].equals("0") && values[6].equals("0"))){
System.out.print(values[2] + " win");
return true;
}
//Check verticals
for(int x = 0;x < 9;x+=3){
if((values[0+x].equals("X") && values[1+x].equals("X") && values[2+x].equals("X")) || (values[0+x].equals("0") && values[1+x].equals("0") && values[2+x].equals("0"))){
System.out.print(values[0+x] + " win");
return true;
}
}
//Checks horizontal
for(int x = 0;x < 3;x++){
if((values[0+x].equals("X") && values[3+x].equals("X") && values[6+x].equals("X")) || (values[0+x].equals("0") && values[3+x].equals("0") && values[6+x].equals("0"))){
System.out.print(values[0+x] + " win");
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
String[] game = {" ", " ", " ", " ", " ", " ", " ", " ", " "};
String[] players = {"X", "0"};
for(int x = 0;x < 9;x++){
System.out.print(players[x%2] + ": ");
int currentPlay = read.nextInt();
while(currentPlay < 1 || currentPlay > 9 || game[currentPlay -1] != " "){
System.out.print("Invalid, play again: ");
currentPlay = read.nextInt();
}
if(x % 2 == 0){
game[currentPlay -1] = "X";
}
else{
game[currentPlay -1] = "0";
}
System.out.printf("%s | %s | %s\n%s | %s | %s\n%s | %s | %s\n", game[0], game[1], game[2], game[3], game[4], game[5], game[6], game[7], game[8]);
if(test(game)){
break;
}
if(!test(game) && x == 8){
System.out.print("Tie");
}
}
}
}