Java-Chars可以向左旋转但不能向右旋转?

时间:2014-10-28 11:22:56

标签: java text rotation

其中:Roteer =旋转, Links = Left,Rechts = Right ....

似乎如果你输入“Oliebol”,3输入roteerNaarLinks,输出将是'bololie',这应该发生。但是如果你输入“Oliebol”,1输入roteerNaarRechts,输出将是'lOliebo'但它应该变成'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;
        }
}

2 个答案:

答案 0 :(得分:0)

for永远不会在roteerNaarRechts中执行。您设置aantal = n然后设置y = n,然后您说循环应该在y > aantal执行时永远不会发生。将其更改为

  

for(int y = n; y&gt; = 0; y - )

答案 1 :(得分: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));
        }
    }
}