Home > Mobile >  trying to print array items on different lines
trying to print array items on different lines

Time:01-28

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.

CodePudding user response:

The arraylist index start from 0 in java hence you need to start the loop in displayCharacters method from 0 ,now you might have to tweak your logic for the pattern you want to display.

CodePudding user response:

Change this method and try it, the array start at the 0 position:

    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)   "|");
            }
        }

    }
  •  Tags:  
  • Related