我是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})
};
calss 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
函数,但程序突然停止执行。有人可以帮帮我。
提前谢谢。
答案 0 :(得分:1)
你试图在同一个地方做太多事情,类Test
的构造函数。
将初始状态的赋值保留给构造函数。将合并代码放在一个单独的方法中,并将代码转换为String
,也可以使用单独的方法。
另外,Test的成员不应该是静态的,否则混淆了。
这将是遵循这些建议的更正代码:
Main.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);
}
}
Test.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;
}
}