1

我有一个程序,它会找到作为命令行参数给出的单词的所有可能排列,但是我无法从程序中获得任何输出,程序编译得很好,当我运行完程序时,我可以'看不出有什么问题。有任何想法吗?

    import java.io.*;
02   
03  public class Anagrams
04  {
05      private static char [] word;
06      private static char [] permutation;
07      private static boolean [] characterUsed;
08   
09       
10       
11      public static void main(String [] args)throws Exception
12      {
13        
14         word = args[0].toCharArray();
15         permutation = new char[word.length];
16         characterUsed =  new boolean[word.length];
17         printPermutations(0);
18      }//main
19       
20     private static void printPermutations(int currentIndex)throws Exception          
02     {
03   
04      if(currentIndex == permutation.length)
05          System.out.println(permutation);
06      else
07      {
08          for(int index=0;index<word.length-1;index++)
09          {
10  //if the character at that index hasn't been used       
11             if(!characterUsed[index]);
12              {
13                 //mark character at this position as in use
14                 characterUsed[index] = true;
15                 //put the character in the permutation
16                permutation[index]= word[currentIndex];
17                 printPermutations(currentIndex +1);
18                 characterUsed[index] = false;
19               }//if
20           }//for
21         }//else
22       }//printPermutation
41  }//Anagrams
4

4 回答 4

2

改变

permutations[index] = permutations[currentIndex];

permutations[index] = argument[currentIndex];

premutation尚未预先填充,因此您始终将其分配给空字符。

将来做类似的事情System.out.println("<"+myString+">");对这类问题很有帮助。

并改变

for (int index = 0; index < argument.length-1; index++)

for (int index = 0; index < argument.length; index++)

于 2012-05-03T16:36:56.997 回答
2

不确定这是否是唯一的问题,但这条线看起来也很可疑:

for (int index = 0; index < argument.length - 1; index++)

您的意思是不要使用char数组中的最后一个吗?你可能的意思是:

for (int index = 0; index <= argument.length - 1; index++)

或者

for (int index = 0; index < argument.length; index++)
于 2012-05-03T16:45:38.037 回答
1

它不打印任何内容的原因是因为 for 循环中的错误。尝试

for (int index = 0; index < argument.length; index++)

于 2012-05-03T16:46:42.457 回答
1

我相信问题出在第 11 行和第 12 行。你真的打算拥有 ; 在 if 条件结束时?

10  //if the character at that index hasn't been used       
11             if(!characterUsed[index]);

希望有帮助..

于 2012-05-27T23:54:40.537 回答