E
E
Egor Safonov2020-04-16 21:06:42
Java
Egor Safonov, 2020-04-16 21:06:42

How to return a value from a loop?

Good afternoon !
I am writing a code for a game of tic-tac-toe, at the moment I am trying to write a win check. Got a question.
There is a method that checks (in this case, verticals), how can I return a variable value from this method, provided that the cycle should not stop its check. When I write return in a loop, it terminates its action, which is not suitable for my case, because then all verticals are not checked (but only the first one). I am attaching a piece of code.

public String checkVertical (Field field){
      Point point1 = new Point(); //создание объекта фигурки
      Point point2 = new Point(); //создание объекта фигурки
      Point point3 = new Point(); //создание объекта фигурки
    String x = null; //переменная которую в итоге вернем для финальной проверки победителя
        for (int i = 0; i < field.getSize(); i++){
              //проверка по координатам
      point1.x = i; 
      point2.x = i;
      point3.x = i;
      point1.y = 0;
      point2.y = 1;
      point3.y = 2;
      x = checkThreePoint(point1, point2, point3, field) ; // данный метод проверяет фигурки на совпадение(если есть 3 из 3 то возвращается победитель, иначе null
      if (x != null) {
        return x; //эта проверка остановит цикл, что неверно
      }
      else{ 
        return null;
      }
    }
    return x; // тут должен вернуться итоговый победитель
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Vodakov, 2020-04-16
@S_h_doc

Remove then you will have an exit from the loop, at the first detection of a triple, which is logical, why check further if the triple is found. Or after going through all iterations of the loop. As far as code quality is concerned, null is not a common thing to return in java, it's logical to use boolean for that. And the variable names are worth working on. else { return null;}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question