2014-08-28 58 views
1

我似乎無法確定我的代碼出了什麼問題。在閱讀了String類之後,我嘗試用短得多的代碼向後打印迴文,但除了執行換行符之外,控制檯上什麼都沒有。 我認爲這個問題可能來自於for語句中的條件表達式,因爲當我使用「i < = l & & i> -1」並用System.print(i +「」)調試它時,我得到了列表中的數字範圍從17到0.那麼,當前表達式有什麼問題,爲什麼我不能使用「i < l & & i> -1」?有沒有什麼是非法的,因爲我打算使用從16到0的數字呢?for循環中的條件表達式不按預期方式運行

public class StephenWork 
{ 
    private String objString ; 
    private int index; 

    private void makeString (String objString) 
    { 
     this.objString = objString; 
    } 

    private char[] printBackwards() 
    { 
     int length = objString.length(); 
     char [] backwards = new char [length]; 

     for (index = length ; index < length && index > -1 ; index--) 
     { 
      backwards [index] = objString.charAt(index); 
     } 

     return backwards; 
    } 

    public static void main (String ... args) 
    { 
     String palindrome = "tod saw I was dot"; 

     int l = palindrome.length(); 
     char [] backwards = new char [l]; 

     for (int i = l; i < l && i > -1 ; i--) 
     { 

      //System.out.println(i); //I was using this to debug the value of i 
      backwards [i] = palindrome.charAt(i); 
     } 

     String printPalin = new String (backwards); 
     System.out.println(printPalin); 

     StephenWork example = new StephenWork(); 
     example.makeString("I love Java"); 
     System.out.println(example.printBackwards()); 
    } 
} 
+0

如果在第一次迭代中'i = l',它不會通過條件檢查'i Blorgbeard 2014-08-28 00:56:25

+0

for(int i = l; i> -1; i--) – Donal 2014-08-28 00:58:07

+0

'for(init; condition; increment){body}'相當於'init; while(condition){body;增量; }' - 如果你將for循環翻譯成這種形式,問題應該會變得更加清晰。 – Blorgbeard 2014-08-28 01:00:46

回答

1

索引設置爲相同的值長,所以循環不會因爲條件最初是錯誤的而執行。

0

您的問題是在你的for循環第一部分:

for(index = length ; index < length ... 

for(int i = l; i < l ... 

是你會產生問題。如果index設置爲length的值,則它不小於長度,因此index < length返回false並且for循環將被完全跳過。與您的il for循環一樣。

,而不是你應該初始化到length - 1

for (index = length - 1 ; index < length && index > -1; index--) 
    backwards [index] = objString.charAt(index); 

修改你以同樣的方式等循環:

for (int i = l - 1; i < l && i > -1 ; i--) 
    backwards [i] = palindrome.charAt(i); 
+0

謝謝。我現在明白了。它必須是一個新手。我對自己很確定。你能把我放在正確的軌道上嗎?我想讓我通過迴文索引來運行。 – NyproTheGeek 2014-08-28 01:26:29

+0

從最後一個索引開始向下。 – NyproTheGeek 2014-08-28 01:33:48

相關問題