Reputation: 39
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.
Upvotes: 0
Views: 50
Reputation: 90
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) + "|");
}
}
}
Upvotes: 1
Reputation: 777
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.
Upvotes: 0