2017-02-26 70 views
0
private static String shift(String p, int shift){ 
    String s = ""; 
    int len = p.length(); 
    for(int x = 0; x < len; x++){ 
     char c = (char)(p.charAt(x) + shift); 
     if (c == ' '){ // this right here isn't working 
      s += " "; 
     } else if (c > 'z'){ 
      s += (char)(p.charAt(x) - (26-shift)); 
     } 
     else { 
      s += (char)(p.charAt(x) + shift); 
     } 
    } 
    return s; 
} 

示例輸出:qer $ hyhi(「$」曾經是一個空格)。爲什麼空間不能像它應該那樣保持空間?相反,它仍然遵循轉換過程。爲什麼不是這個凱撒輪班工作

+1

什麼語言這應該是什麼? –

回答

1

問題是你正在比較已經移位的字符空間。

有幾種方法來修復這個bug,其中之一是以下(固定一些小的問題):

private static String shift(String p, int shift){ 
    StringBuilder s = new StringBuilder(); //better using a mutable object than creating a new string in each iteration 
    int len = p.length(); 
    for(int x = 0; x < len; x++){ 
     char c = p.charAt(x); //no need for casting 
     if (c != ' '){ // this should work now 
      c += shift; 
      if (c > 'z'){ //we assume c is in the 'a-z' range, ignoring 'A-Z' 
       c -= 'z'; 
      } 
     } 
     s.append(c); 
    } 
    return s.toString(); 
} 
+0

不能滿足這個要求!這是一個完美的,易於理解的解決方案!非常感謝你! – CarbonZonda