打印集合的所有子集/将字符串转换为字符[]的Java程序
我想递归地找到集合的所有子集,下面是我的代码。我的问题在于这部分:打印集合的所有子集/将字符串转换为字符[]的Java程序,java,recursion,subset,Java,Recursion,Subset,我想递归地找到集合的所有子集,下面是我的代码。我的问题在于这部分: 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[]
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)
我想用这部分代码从用户那里获取集合,并将其放入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);
}
}
//打印集合的所有子集的Java程序
导入java.io.IOException;
导入java.util.Scanner;
班长
{
//打印给定集合的所有子集[]
静态void打印子集(字符集[])
{
int n=设置长度;
//运行循环以打印所有2^n
//obe的一个子集
对于(int i=0;i<(1用以下代码替换错误代码行
char[] set = in.nextLine().replaceAll("[?!^]","").toCharArray();
您可以通过在.nextLine().tocharray()中调用来将字符串转换为char[]
。您不能在char[]
上调用split(…)
。看起来您所需要做的只是将.nextLine()中的char[]set=in.tocharray().split((?!^);
替换为char[]set=in.nextLine().split(“?!”).toCharArray();
根据给定的异常情况。@BalliticBlazesplit((?!^)”.toCharArray()
?数组没有真正的方法,我不确定是什么String[].toCharArray
甚至可以…啊,忘了这一点,拆分似乎比我想象的更困难。可能是多维字符数组?是的,我尝试了,但我得到了另一个错误:线程“main”java.lang中出现异常。错误:未解决的编译问题:无法对数组类型字符串[]调用toCharArray()在subsetGeek.Main.Main(Main.java:35)