尝试在不同的行上打印数组项

trying to print array items on different lines

enter code here
package Question2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class RandomAlphabets {
//    declaring and initializing Random class for generating random letters.
    Random random = new Random();
    ArrayList<Character> randomCharacters = new ArrayList<>();

//    method to generate Random characters.

    public int generateRandomCharacter(){
        char randomCharacter=0;
        for(int i = 1 ; i <= 16; i++){
            randomCharacter = (char)(random.nextInt(26)+'a');
            randomCharacters.add(randomCharacter );
        }
        return randomCharacter;
    }


//    message to display Random Characters.

    public void displayCharacters() {
        for (int i = 1; i < randomCharacters.size(); i++) {
            if (i % 4 == 0) {
                System.out.println(randomCharacters.get(i));
            } else {
                System.out.print(randomCharacters.get(i) + "|");
            }
        }

        }
    }

i wanted to achieve this output w|s|b|e h|n|f|f y|h|c|t l|o|f|g but I am getting this output instead w|s|b|e h|n|f|f y|h|c|t l|o|f| have no idea why I am getting this out.

arraylist 索引从 0 开始 java 因此你需要在 displayCharacters 方法中从 0 开始循环,现在你可能需要调整你想要显示的模式的逻辑。

换个方法试试,数组从0位置开始:

public void displayCharacters() {
    for (int i = 1; i <= randomCharacters.size(); i++) {
        if (i % 4 == 0) {
            System.out.println(randomCharacters.get(i - 1));
        } else {
            System.out.print(randomCharacters.get(i - 1) + "|");
        }
    }
}