我是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函数,但是该程序突然停止执行。有人可以帮我吗。
先感谢您。

最佳答案

您正在尝试在同一位置(类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;
    }
}

10-04 11:22
查看更多