2014-10-28 126 views
1

其中:Roteer =旋轉, 鏈接=左,Rechts =右....Java-Chars可以向左旋轉但不能向右旋轉?

看來,如果你輸入 「Oliebol」,3到roteerNaarLinks,輸出將是 'bololie',這是爲了發生。但是如果你輸入「Oliebol」,1輸入roteerNaarRechts,輸出結果將是'lolbo',但它應該變成'llieboo',我該如何解決這個問題? :)

public class Roteer { 

     public static String roteerNaarLinks(String invoer, int n){ 
      String in = invoer; 
      int aantal = n; 

      for(int i = 0; i< aantal; i++){ 
       char firstLetter = in.charAt(0); 
       in = in.substring(1); 
       in = in + firstLetter; 
      } 

      return in; 
     } 
     public static String roteerNaarRechts(String invoer, int n){ 
      String in = invoer; 
      int aantal = n; 

      for(int y = n; y > aantal; y--){ 
       char lastLetter = in.charAt(in.length()-1); 
       in = in.substring(1); 
       in = lastLetter + in; 
      } 

      return in; 
     } 
} 
+1

我沒有得到那個輸出。對於'roteerNaarLinks(「Oliebol」,3)'我得到'ebolOli'和'roteerNaarRets(「Oliebol」,1)'我得到'Oliebol' – Ian2thedv 2014-10-28 11:45:20

+0

是的,由於某種原因,roteerNaarLinks確實有效,但是roteerNaarRechts沒有,它應該給'lOliebo' – Ivaro18 2014-10-28 11:48:16

+0

爲什麼有'for(int y = n; y> aantal; y - ){'而不僅僅是for(int i = 0; i 2014-10-28 11:53:02

回答

0

for絕不會roteerNaarRechts執行。您設置了aantal = n,然後設置了y = n,然後您說該循環應該執行,而y > aantal這從來就不是真的。它更改爲

對(INT Y = N; Y> = 0; y--)

0

代替通過字符串聯輸出字符串的字符的我建議以下溶液(其仍然可以根據您的要求調整)

public class Roteer { 

    public static String roteerNaarLinks(String invoer, int n) { 
     StringBuilder sb = new StringBuilder(invoer.length() * 2); 
     sb.append(invoer).append(invoer); 
     int offset = n % invoer.length(); 
     return sb.substring(offset, offset + invoer.length()); 
    } 

    public static String roteerNaarRechts(String invoer, int n) { 
     StringBuilder sb = new StringBuilder(invoer.length() * 2); 
     sb.append(invoer).append(invoer); 
     int offset = invoer.length() - n % invoer.length(); 
     return sb.substring(offset, offset + invoer.length()); 
    } 

    public static void main(String[] args) { 
     final String inputString = "Oliebol"; 
     System.out.println("--- roteerNaarLinks"); 
     for (int i = 0; i <= inputString.length(); i++) { 
      System.out.println(roteerNaarLinks(inputString, i)); 
     } 

     System.out.println("--- roteerNaarRechts"); 
     for (int i = 0; i <= inputString.length(); i++) { 
      System.out.println(roteerNaarRechts(inputString, i)); 
     } 
    } 
} 
相關問題