【发布时间】:2015-02-26 02:15:48
【问题描述】:
我正在尝试将用户的输入添加到我的排列列表中,但是当我接受用户输入时,程序只是继续运行。在第三次输入后按回车键时,我没有得到任何排列。这是我的代码:
import java.util.ArrayList;
import java.util.Scanner;
/**
This program demonstrates the permutation generator.
*/
public class PermutationGeneratorDemo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a 4 letter word: ");
String word1 = scan.next();
System.out.println("Enter a 5 letter word: ");
String word2 = scan.next();
System.out.println("Enter a 6 letter word: ");
String word3 = scan.next();
PermutationGenerator generator = new PermutationGenerator(word1 + word2 + word3);
ArrayList<String> permutations = generator.getPermutations();
for (String s : permutations)
{
System.out.println(s);
}
}
}
排列代码:
import java.util.ArrayList;
/**
This class generates permutations of a word.
*/
public class PermutationGenerator
{
private String word;
/**
Constructs a permutation generator.
@param aWord the word to permute
*/
public PermutationGenerator(String aWord)
{
word = aWord;
}
PermutationGenerator(String[] wordList) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
Gets all permutations of a given word.
*/
public ArrayList<String> getPermutations()
{
ArrayList<String> permutations = new ArrayList<String>();
// The empty string has a single permutation: itself
if (word.length() == 0)
{
permutations.add(word);
return permutations;
}
// Loop through all character positions
for (int i = 0; i < word.length(); i++)
{
// Form a simpler word by removing the ith character
String shorterWord = word.substring(0, i)
+ word.substring(i + 1);
// Generate all permutations of the simpler word
PermutationGenerator shorterPermutationGenerator
= new PermutationGenerator(shorterWord);
ArrayList<String> shorterWordPermutations
= shorterPermutationGenerator.getPermutations();
// Add the removed character to the front of
// each permutation of the simpler word,
for (String s : shorterWordPermutations)
{
permutations.add(word.charAt(i) + s);
}
}
// Return all permutations
return permutations;
}
}
【问题讨论】:
-
如果您包含实际生成排列的代码会有所帮助...
-
@AmirAfghani 是正确的,只是想我会补充一点:
Scanner#next读取下一个String默认由space分隔。Scanner#nextLine读入由new-line字符分隔的下一行。 -
排列代码现在也在那里。我对Java相当陌生。当我将 next() 更改为 nextLine() 时,我仍然遇到同样的问题。
-
您的算法不会生成排列。修改您的程序以接受 1 个单词并输入“aaaa”。看看你得到了什么......如果这不是学术练习,请考虑使用 Guava 的 Collections2.permutations 方法
标签: java arrays input arraylist java.util.scanner