0

My java do while loop is supposed to check user input however when the program is run, the program prints "Enter coordinates" and goes ahead to print "You should enter numbers", ignoring my conditional statement, then loops back to "Enter coordinates" What might be wrong?

do{
            System.out.print("Enter the coordinates: ");
            String input = scanner.nextLine();
            String[] Compass = input.split(" ");

            if(Compass.length == 2 && Compass[0].matches("\\d+") && Compass[1].matches("\\d+")) {
                int xAxis = Integer.parseInt(Compass[0]);
                int yAxis = Integer.parseInt(Compass[1]);
                numeric = true;
                if (xAxis < 1 || xAxis > 3 || yAxis < 1 || yAxis > 3) { //ensure coordinates are between 1 and 3
                    System.out.println("Coordinates should be from 1 to 3!");
                    withinThree = false;
                } else {
                    //inputs that pass all tests can proceed
                    //assign array indices to respective coordinates
                    g = yAxis - 1;
                    h = xAxis - 1;
                }
                while (r < matrix.length()) { //count number of x and o for future use
                    if (matrix.charAt(r) == 'X') {
                        counterx++;
                    } else if (matrix.charAt(r) == 'O') {
                        countero++;
                    }
                    r++;
                }

                //creat an array from the X and Os
                for (int ki = 0; ki < 3; ki++) {
                    for (int li = 0; li < 3 && d < matrix.length(); li++, d++) {//iterate over each character in the string and assign
                        // them to a position on the array
                        if (matrix.charAt(d) == 'O' || matrix.charAt(d) == 'X') {
                            wordsArray[ki][li] = matrix.charAt(d);
                        } else if (matrix.charAt(d) == '_') { // where user inputs an underscore make it an empty cell
                            wordsArray[ki][li] = ' ';
                        }
                    }
                }


                if ((wordsArray[g][h] != ch1)) { //if  coordinates do not correspond to an empty cell
                    System.out.println("This cell is occupied! Choose another one!");
                    notOccupied = false;
                }
            }else {
                    numeric = false;
                    System.out.println("You should enter numbers");
                }


        } while ( !notOccupied || !withinThree || !numeric);

This is the output: "Enter the coordinates: You should enter numbers Enter the coordinates: ".

At the first run of the program, it goes ahead to print "You should enter numbers", e=despite not meeting the condition to print it.

Ugo
  • 11
  • 3

0 Answers0