【问题标题】:A Java program to print all subsets of a set/ Converting String to char[]一个 Java 程序,用于打印集合的所有子集/将字符串转换为 char[]
【发布时间】:2018-06-10 10:38:27
【问题描述】:

我想递归查找集合的所有子集,这是我拥有的代码。我的问题在于这部分:

char[] set = in.nextLine().toCharArray().split("(?!^)");

当我运行这段代码时,我得到了这个错误,我不知道如何解决它。

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Cannot invoke split(String) on the array type char[]

at subsetGeek.Main.main(Main.java:35)

我想使用这部分代码从用户那里获取 Set 并将其放入 char[] 中,然后显示子集。

// A Java program to print all subsets of a set
    import java.io.IOException;
    import java.util.Scanner;
    class Main
    {
        // Print all subsets of given set[]
        static void printSubsets(char set[])
        {
            int n = set.length;

        // Run a loop for printing all 2^n
        // subsets one by obe
        for (int i = 0; i < (1<<n); i++)
        {
            System.out.print("{ ");

            // Print current subset
            for (int j = 0; j < n; j++)

                // (1<<j) is a number with jth bit 1
                // so when we 'and' them with the
                // subset number we get which numbers
                // are present in the subset and which
                // are not
                if ((i & (1 << j)) > 0)
                    System.out.print(set[j] + " ");

            System.out.println("}");
        }
    }

    // Driver code
    public static void main(String[] args)
    {   Scanner in = new Scanner(System.in);
        char[] set = in.nextLine().toCharArray().split("(?!^)");
        //char set[] = {'a', 'b', 'c'};
        printSubsets(set);
    }
}

还有什么可以用我的那部分代码替换的吗?

【问题讨论】:

  • 您可以通过调用in.nextLine().toCharArray()String 转换为char[]。您不能在 char[] 上调用 split(...)
  • 看起来您需要做的就是根据给出的异常将char[] set = in.nextLine().toCharArray().split("(?!^)"); 替换为char[] set = in.nextLine().split("(?!^)").toCharArray();
  • @BallisticBlaze split("(?!^)").toCharArray()?数组并没有真正的方法,我不确定String[].toCharArray 会做什么......
  • 啊,忘记了,拆分似乎比我想象的要难。也许是一个多维字符数组?
  • 是的,我试过了,但我得到了另一个错误:线程“main”中的异常 java.lang.Error:未解决的编译问题:无法在 subsetGeek 的数组类型 String[] 上调用 toCharArray()。 Main.main(Main.java:35)

标签: java recursion subset


【解决方案1】:

用下面的代码替换你的错误代码行。

char[] set = in.nextLine().replaceAll("[?!^]","").toCharArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多