我想創建兩種狀態(1和0)的所有組合。 如果我用兩個for-loop做到這一點,這是有效的。但是當我使用自我調用功能時,它沒有。有人可以告訴我爲什麼嗎?創建所有組合Java
for循環:
public class Counter {
public Counter() {
loop(iter);
for (int i=0; i < 2; i++) {
for (int i2=0; i2 < 2; i2++) {
System.out.println(Integer.toString(i)+Integer.toString(i2));
}
}
}
public static void main(String args[]){
new Counter();
}
}
自我調用功能:
class Stringhelper {
public Stringhelper() {
}
public String getstring(String string,int beginning,int ending) {
if (string.length() != 0) {
String newstring="";
for (int iter=Math.abs(beginning); iter < ending && iter < string.length(); iter=iter+1) {
newstring=newstring+Character.toString(string.charAt(iter));
}
return newstring;
}
else {
return "";
}
}
}
public class Counter {
public String abil="";
public int iter=1;
public Stringhelper shelper=new Stringhelper();
public void loop(int iter) {
for (int i=0; i < 2; i++) {
abil=abil+Integer.toString(i);
if (iter==0) {
System.out.println(abil);
abil=shelper.getstring(abil,0,abil.length()-1);
}
else {
loop(iter-1);
}
}
}
public Counter() {
loop(iter);
}
public static void main(String args[]){
new Counter();
}
}
而且使用自調用函數的輸出爲00,01,010,011,而不是00,01,10,11
感謝,但你可以請解釋爲什麼輸出爲:00,01,010,011代替:00,01,10,11 – user7185318
爲什麼不使用原來的for循環?遞歸應該只在特定情況下使用,這絕對不是其中之一。它也比原來的for循環慢。此外,使用更好的命名約定,現在閱讀代碼非常困難。 問題出在 abil = shelper.getstring(abil,0,abil.length() - 1); 但是我現在很難調試,其他用戶似乎同意,因爲你被低估了 – Gabrielus
因此,總之:將不同的功能分成單獨的方法,以主動的方式命名變量,而不要讓行長度超過44個字符 – Gabrielus