#java #if-statement
#java #if-statement
Вопрос:
private int getNextNodesDirection(Pair<Integer, Integer> current, Pair<Integer, Integer> nextNode, Robot target) {
System.out.println("current x:" current.getSecond());
System.out.println("current y:" current.getFirst());
System.out.println("next x:" nextNode.getSecond());
System.out.println("next y:" nextNode.getFirst());
if (target.getCurrentDirection().equals(IWorld.Direction.UP)) {
//if y increases and x stays the same
if (nextNode.getFirst() > current.getFirst() amp;amp; nextNode.getSecond().equals(current.getFirst())) {
return 0;
}
// if x increases and y stays the same
else if (nextNode.getSecond() > current.getSecond() amp;amp; nextNode.getFirst().equals( current.getFirst())) {
return 1;
}
while (index < endIndex){
int fSteps = 0;
int direction = getNextNodesDirection(nodeList.get(index), nodeList.get(index 1), target);
if (direction == 1){
cost =1;
target.handleCommand(new RightCommand());
}
else if (direction == 2){
cost =2;
target.handleCommand(new RightCommand());
target.handleCommand(new RightCommand());
}
else if (direction == 3){
cost =1;
target.handleCommand(new LeftCommand());
}
while (direction == 0){
fSteps = 1;
cost =fSteps;
index =1;
if(nodeList.get(index).getSecond() == (end.getX()) amp;amp; nodeList.get(index).getFirst() == end.getY()){
break;
}
direction = getNextNodesDirection(nodeList.get(index), nodeList.get(index 1), target);
Поэтому, когда программа запускается, она входит в getNextNodesDirection и выполняется, как ожидалось, но во второй раз, хотя все условия выполнены, она просто передает инструкцию. Почему? Я бы хотел, чтобы он возвращал 0, в то время nextNode.getFirst()
как больше current.getFirst
и nextNode.getSecond()
равно current.getSecond()
Я сделал скриншот здесь, в IntelliJ, во время отладки вы можете ясно видеть, что y увеличивается, а x остается неизменным, но он передает условие «выполнено» и продолжается. Почему?
Язык — Java 11, ОС — Debian на виртуальной машине.
Комментарии:
1.
nextNode.getSecond().equals(current.getFirst())
равно false . Вы имели в видуnextNode.getSecond().equals(current.getSecond())
?2. Не вдаваясь в подробности, я хотел бы порекомендовать вам переработать код. Например, извлеките логическое выражение, чтобы его можно было заменить
nextNode.getFirst() > current.getFirst()
наisNextNodeGreater
. Это сделает ваш код намного более читабельным, а дополнительным преимуществом является то, что вы можете увидеть результат выполнения условия в вашем отладчике.3. @talex большое вам спасибо, не могу поверить, что я это пропустил. Было поздно.