【发布时间】: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)