1

我正在尝试制作一个简单的程序,该程序将接收一个包含 4 个单词的字符串,然后将该字符串拆分为 4 个单词,并打印这 4 个单词的所有可能排列

这是源代码,正则表达式在第 21 行,我不确定它是否正确。而且它真的不喜欢我的嵌套 for 循环

 /**


 * Author: peaceblaster
 * Date 9/10/2013
 * Title: hw3
 * Purpose: To take in 4 words as a single string, then prints all permutations of the four words
 */

//import stuff
import java.util.Scanner;
public class hw3 {
    public static void main(String[] args){
        //declarations:
        Scanner in = new Scanner(System.in);
        String input = new String();
                String[] wordArray = new String[4];
                int a,b,c,d;
        //input
        System.out.println("Input 4 words: ");
        input = in.next();
        //regex
        wordArray = input.split("^*[^\s]|\s*\s|*$"); //splits string into array containing each words as a string
                                    // ^* finds first word \s*\s finds words surrounded by spaces *$ finds final word
        //output
        for (a=1; a=<4; a++){
            for (b=1; b=<4; b++){
                for (c=1; c=<4; c++){
                    for (d=1; d=<4; d++){
                        System.out.println(wordArray[%a] + " " + wordArray[%b] + " " + wordArray[%c] + " " + wordArray[%d]);  //uses nested for loops to print permutations as opposed to hard-coding
                    }
                }
            }
        }
    }
}
4

3 回答 3

1

通过获取输入

String words[] = new String[4];

for (int i = 0; i < words.length; ++i) {
    words[i] = in.nextLine(); 
}

//or
String words[] = in.nextLine().split("\\s+"); //space separated words.

您不需要%在变量名之前使用

System.out.println(wordArray[a] + " " + wordArray[b] + " " + wordArray[c] + " " + wordArray[d]);
于 2013-09-10T17:21:33.247 回答
1

数组是基于 0 的,你的 for 循环是错误的。我还为您的排列添加了不多次使用同一个词的条件。它应该看起来像:

for (a = 0; a < 4; a++) {
    for (b = 0; b < 4; b++) {
        if (b == a) continue;
        for (c = 0; c < 4; c++) {
            if (c == a || c == b) continue;
            for (d = 0; d < 4; d++) {
                if (d == a || d == b || d == c) continue;
                System.out.println(wordArray[a] + " " + wordArray[b] + " " + wordArray[c] + " " + wordArray[d]);
            }
        }
    }
}

此外,就像提到的 bsd 一样,您的拆分表达式应该是:

wordArray = input.split("\\s+");
于 2013-09-10T17:47:19.750 回答
0

Java 的split方法需要一个描述“分隔符”字符串的正则表达式,而不是您想要留下的字符串。你似乎假设后者。另请注意,由于您正在描述分隔单词的字符串,因此您无需考虑目标开头或结尾处没有分隔符的可能性。出于同样的原因,如果分隔符字符串确实出现在开头或结尾,split则对于这两种情况都不会返回空字符串。

于 2013-09-10T17:23:24.553 回答