其中: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;
}
}
答案 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));
}
}
}