0

I have to create a program for school that asks the user how many letter he wants to create, and if he says for example 8, it will create the following:

char[] letters = new char[8]

It will then assign a random letter to each array indexes (0 to 7) and then the user has to guess the code comprised of 8 letters.

All I know about using random class is this:

letterValue = (char) (rand.nextInt(26) + 'a'); // Creates random letters a to z.

So how would I assign the 8 random letters to each index?

0

1 Answer 1

1

Use a for loop for the total number of characters that user inputted.
Each random character you generate needs to be stored at an index in the array.

int numberOfCharacters = 8;
char[] letters = new char[numberOfCharacters];
Random random = new Random();
for(int i = 0; i < numberOfCharacters; i++) {
    letters[i] = (char) (random.nextInt(26) + 'a');
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Very helpful and simple to understand.
@Majestic Welcome! Can you close out the question by accepting the answer?
Sorry I'm new to Stackoverflow, so new to the features, but here you go. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.