2015-02-23 51 views
-2

我想要發生的事情:我想將當前值保存到char變量中。因此,如果當前值!=持有者值應該打印左移,但是噹噹前值等於持有者值時,它應該向前移動。爲什麼char =='L'和char!='L'具有相同的輸出?

問題:char值持有者與其他語句輸出相同。 假設是什麼問題?

僅基於循環的方向。

public void reconstructPath(Node node) { 
    while (node.parent != null) { 
     //DIRECTIONS: L - Left, R - Right, U - up, D - Down 
     int nextX, nextY; 
     char direction = 0; 
     char current = 0; 
     nextX = node.parent.x; 
     nextY = node.parent.y; 

     if(nextX == node.x) 
     { 

      if(nextY > node.y){ 
       direction = 'D'; 
      } 
      else{ 
       direction = 'U'; 


      } 

     }else if(nextY == node.y){ 

      if(nextX > node.x){    
       direction = 'R'; 

      }else{ 
       direction = 'L'; 
       if(direction != 'L'){ 
        System.out.println("move forward"); 
       }else{ 
        char holder = direction; 
        System.out.println("move up"); 
       } 

      } 
     } 

     System.out.printf("Traceback: (%d, %d) go %c\n", node.x, node.y, direction); 
     node = node.parent; 

    } 

} 

輸出:

move L // first L should be left. 
Traceback: (4, 1) go L 
move L // this should move forward instead of left. 
Traceback: (3, 1) go L 
move L 
Traceback: (2, 1) go L 
+2

你爲什麼會這麼做? '方向='L';如果(方向!='L')'你迫使它到'L',然後立即檢查它? – 2015-02-23 18:21:33

+0

這將有助於看到'方向'聲明在哪裏。如果它被聲明爲可以解釋行爲的'String'。 – mkasberg 2015-02-23 18:21:33

+1

使用具有斷點的調試器可以幫助您在將'direction'與'L''進行比較時發現'direction'總是等於'L''。 – 2015-02-23 18:24:14

回答

2

考慮這連續兩行:

direction = 'L'; 
    if(direction != 'L') 

是否缺少後的第一個密切的支柱?

+0

不,我沒有失去任何大括號。 – Kyoshiro 2015-02-23 18:31:42

+0

如果你沒有遺漏任何大括號,那麼請將代碼重寫爲'direction ='L'; System.out.println(「向上移動」);'---因爲這與您現在的代碼完全相同,只是刪除了死代碼。 – 2015-02-23 18:43:40

+1

是的,你錯過了一個支架 - 或者更準確 - 你的支架位置不對。我引用的代碼是「無稽之談」。它在語法上是正確的,但並不意味着任何有用的東西。正如Marko指出的那樣,if條件總是錯誤的,因爲該賦值只是設置了您正在測試的值。放入支架,將不必要的支架拆下,問題就會消失。 – 2015-02-23 21:27:41

0

當您找到「L」時,您必須檢查以前的值是否爲「L」。

要實現此解決方案,你要記住你的舊值:

public void reconstructPath(Node node) { 
    char lastDirection = (char)-1; 
    while (node.parent != null) { 
     //DIRECTIONS: L - Left, R - Right, U - up, D - Down 
     int nextX, nextY; 
     char direction = 0; 
     char current = 0; 
     nextX = node.parent.x; 
     nextY = node.parent.y; 

     if(nextX == node.x) 
     { 

      if(nextY > node.y){ 
       direction = 'D'; 
      } 
      else{ 
       direction = 'U'; 


      } 

     }else if(nextY == node.y){ 

      if(nextX > node.x){    
       direction = 'R'; 

      }else{ 
       direction = 'L'; 
       if(lastDirection == 'L'){ 
        System.out.println("move forward"); 
       }else{ 
        System.out.println("move up"); 
       } 

      } 
     } 
     lastDirection = direction; 
     System.out.printf("Traceback: (%d, %d) go %c\n", node.x, node.y, direction); 
     node = node.parent; 

    } 

} 
+0

仍然是相同的輸出。首先升起來。第二升升。第二個L應該向前移動 – Kyoshiro 2015-02-23 18:47:35

+0

quiblle:這不是一個聲明,它是一個任務。請準確使用技術術語。 – 2015-02-23 21:25:02

+0

你必須記住你的舊值 – 2015-02-23 21:37:53

相關問題