英文:
Java - Generating a list of every permutation of 4 characters
问题
我试图生成字母表前4个字母的所有可能的4字符排列(即aaaa,aaab,aaac,aaad,aaba...)。我想我会使用嵌套的for循环,但是当我运行程序时,for循环似乎完全被跳过,我只看到"Number of chain printed 0"。
我做错了什么?
package com.company;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String suite = new String();
ArrayList<String> list = new ArrayList<String>();
char[] table = {'a', 'b', 'c', 'd'};
char c1;
char c2;
char c3;
char c4;
int total = 0;
for (int j = 0; j <= 3; j++) {
for (int k = 0; k <= 3 ; k++) {
for (int l = 0; l <= 3; l++) {
for (int m = 0; m <= 3; m++) {
c1 = table[j];
c2 = table[k];
c3 = table[l];
c4 = table[m];
suite = Character.toString(c1) + Character.toString(c2) + Character.toString(c3) + Character.toString(c4);
list.add(suite);
System.out.println(suite);
total++;
}
}
}
}
System.out.println("Number of chain printed " + total);
}
}
你的问题在于for循环的条件不正确,应该使用"j <= 3"而不是"j == 3",以及类似的修复其他for循环的条件。这样你就会得到正确的输出。
英文:
I'm trying to generate a list of all possible 4 characters permutation of the first 4 letters of the alphabet (i.e. aaaa, aaab, aaac, aaad, aaba...) I figured I'd go with nested for loop, but when I run the program, the for loops seem to be skipped altogether and I only see the "Number of chain printed 0"
What am doing wrong?
package com.company;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String suite = new String();
ArrayList<String> list = new ArrayList<String>();
char[] table = {'a', 'b', 'c', 'd'};
char c1;
char c2;
char c3;
char c4;
int total = 0;
for (int j = 0; j == 3; j++) {
for (int k = 0; k == 3 ; k++) {
for (int l = 0; l == 3; l++) {
for (int m = 0; m == 3; m++) {
c1 = table[j];
c2 = table[k];
c3 = table[l];
c4 = table[m];
suite = Character.toString(c1) + Character.toString(c2) + Character.toString(c3) + Character.toString(c4);
list.add(suite);
System.out.println(suite);
total++;
}
}
}
}
System.out.println("Number of chain printed " + total);
}
}
答案1
得分: 1
所有的循环条件都不正确;应该是<= 3
,而不是== 3
,这将使循环只在计数器等于3的情况下继续运行—在这种情况下循环甚至不会开始。
for (int j = 0; j <= 3; j++) {
for (int k = 0; k <= 3 ; k++) {
for (int l = 0; l <= 3; l++) {
for (int m = 0; m <= 3; m++) {
英文:
All your looping conditions are incorrect; it should be <= 3
, not == 3
, which would make the loop only continue as long as the counter is equal to 3—the loop will never even start in that case.
for (int j = 0; j <= 3; j++) {
for (int k = 0; k <= 3 ; k++) {
for (int l = 0; l <= 3; l++) {
for (int m = 0; m <= 3; m++) {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论