从String ArrayList获取输入并输出新字符串

时间:2016-10-06 23:06:53

标签: java string for-loop arraylist concatenation

此代码应采用String ArrayList并打印出这些字符串的修改版本,称为" states"。例如:第一个字符串" 3,3,L"应该打印MMMCCCL。目前,当我输入ArrayList goodMoves时:( [3,3,L,1,1,R,3,2,L,0,3,R,3,1,L,2,2,R,2,2 ,L,3,1,R,0,3,L,3,2,R,1,1,L,3,3,R]),代码返回ArrayList中的最后一个状态(" MMMCCCR& #34;)而不是所有11个州:

MMMCCCL

MCR

MMMCCL

CCCR

MMMCL

MMCCR

MMCCL

MMMCR

CCCL

MMMCCR

MCL

MMMCCCR

这是我到目前为止所做的:

// Testing method   
public static void main(String[] args) {

    int missionaries = 3;
    int cannibals = 3;
    boolean BoatState = true;

    // Add initial state
    goodMoves.add(toString(missionaries, cannibals, BoatState));

    // Call checkBoat and explore
    explore(missionaries, cannibals, BoatState, goodMoves, allMovesMade);

    // Print all steps using helper method
    System.out.println(makePicture(goodMoves));

    // Print the total number of operations made
    String finalMoves = ("Number of moves made: " + (goodMoves.size()-1));
    System.out.println(finalMoves);
}

// Create strings of state spaces
public static String makePicture(ArrayList<String> goodMoves) {

    // Initialize strings
    String missString = "";
    String cannString = "";
    String moveString = "";

    // Use input to create printout
    for (String output: goodMoves) {

        // Get numbers/character at each index of string
        char missNum = output.charAt(0);
        char cannNum = output.charAt(2);
        char boatPos = output.charAt(4);

        // Print number of M's and C's then concatenate them together
        missString = new String(new char[missNum]).replace("\0", "M");
        cannString = new String(new char[cannNum]).replace("\0", "C");

        // Concatenate both strings
        moveString = missString + cannString + boatPos + "\n";
        }
    }
    // Return string of current state
    return moveString;
}

如果需要澄清,请告诉我。这个问题参考了常见的传教士和食人族游戏。提前致谢!

更新:问题解决了。感谢您的反馈

3 个答案:

答案 0 :(得分:0)

试试这个moveString = missString + cannString + boatPos +",";

另外,这样做 return moveString.subString(0,moveString.length()-1);它会删除字符串中的最后一个逗号。

答案 1 :(得分:0)

这应该是一个评论,但我没有足够的声誉点来做到这一点。

尝试@Shika A刚刚说的话,并在最后添加+“\ n”。像这样:

moveString = missString + cannString + boatPos +"\n";

这将以不同的方式分隔您的陈述。

答案 2 :(得分:0)

首先,你有一个不必要的if结构。你有if (boatPos == 'L')然后你做了一些事情,然后有else然后做同样的事情。所以只需删除if结构即可。

所以将你的for循环更改为:

// Use input to create printout
for (String output: goodMoves) {

    // Get numbers/character at each index of string
    char missNum = output.charAt(0);
    char cannNum = output.charAt(2);
    char boatPos = output.charAt(4);

    // Print number of M's and C's then concatenate them together
    missString = new String(new char[missNum]).replace("\0", "M");
    cannString = new String(new char[cannNum]).replace("\0", "C");

    // Concatenate both strings
    moveString = missString + cannString + boatPos + "\n";
}

请注意,在最后一行,我添加了"\n"。这是换行符。在计算每个moveString后,它将打印一个新行。如果您需要将换行符放在其他位置(我完全不了解您的代码),那么将其移到其他地方。但添加换行符就是这么简单。