我是 Java 初学者。我用主类创建了一个主程序。这称为 Main.java
。这个主类包含一组数组。这些数组被导入到名为 Test.java
的第二个类中。现在我正在寻找一种方法来连接第二节课末尾的所有数组。我的代码如下所示:
import java.util.Arrays;
public class Main{
public enum State{A,D,H};
Test[] tests = new Test[]{
new Test(new State[]{State.A, State.H, State.A, State.H}),
new Test(new State[]{State.A, State.H, State.A, State.D}),
new Test(new State[]{State.H, State.D, State.A, State.A})
};
类 Test.java 看起来像这样:
import java.util.Arrays;
public class Test{
public static Main.State[] in;
public static Main.State[] in_state= new Main.State[4];
public static String data_in;
Test(Main.State[] in){
this in = in;
this.in_state=in_state;
for( int i=0; i<in.length; i++){
in_state[i]=in[i];
data_in =java.util.Arrays.toString(in_state);
data_in = data_in.replaceAll(",", "");
data_in = data_in.replaceAll(" ","");}
System.out.println( "The input arrays are" +data_in) ;
现在我得到的输出是这样的:
The input arrays are[AHAH]
The input arrays are[AHAD]
The input arrays are[HDAA]
我想取而代之的是 AHAHAHADHDAA。我尝试使用 ArrayUtils.addAll
函数,但程序突然停止执行。有人可以帮帮我吗?
提前谢谢你。
最佳答案
你试图在同一个地方做太多事情,Test
类的构造函数。
将初始状态的分配留给构造函数。将合并代码放在一个单独的方法中,并将要转换为 String
的代码也放在一个单独的方法中。
此外,Test 的成员不应该是静态的,否则会混淆。
这将是遵循这些建议的更正代码:
主.java
public class Main
{
public static enum State
{
A, D, H
};
public static void main(String[] args)
{
Test[] tests = new Test[]
{
new Test(new State[]
{
State.A, State.H, State.A, State.H
}),
new Test(new State[]
{
State.A, State.H, State.A, State.D
}),
new Test(new State[]
{
State.H, State.D, State.A, State.A
})
};
Test testMerged = Test.merge(tests);
System.out.println("The input arrays are" + testMerged);
}
}
测试.java
public class Test
{
static Main.State[] in;
public static Test merge(Test[] tests)
{
int size = calculateSize( tests );
Main.State[] state = new Main.State[size];
int i = 0;
for ( Test test : tests )
{
for ( Main.State s : test.in )
state[i++] = s;
}
return new Test( state );
}
private static int calculateSize(Test[] tests)
{
int result = 0;
for ( Test test : tests )
{
for ( Main.State s : test.in )
++result;
}
return result;
}
Test(Main.State[] in)
{
this.in = in;
}
@Override
public String toString()
{
String result =java.util.Arrays.toString(in);
result = result.replaceAll(",", "");
result = result.replaceAll(" ","");
return result;
}
}
关于java - 如何在 Java 中连接来自不同类的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31605815/