2017-02-26 26 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