Majestic
Majestic

Reputation: 39

Java Random Class that Outputs Letters (A to E)

So I'm creating a program that output 3 random letters from A to E. The issue is that it should also include lowercase A to E( A,a,B,b,C,c,D,d,E,e)

This is what I used to print out a random letter.

letterValue = (char) (rand.nextInt(5) + 'A');
System.out.print(letterValue);

The variable 'letterValue' should print out A to E, both Uppercase and Lowercase.

Upvotes: 0

Views: 132

Answers (2)

Anonymous
Anonymous

Reputation: 86282

        letterValue = (char) (rand.nextInt(5) + 'A');
        if (rand.nextBoolean()) {
            letterValue = Character.toLowerCase(letterValue);
        }
        System.out.print(letterValue);

This is just one way out of many. I’m using your own code and trying not to complicate the task more than necessary. I ran this three times since you wanted 3 random letters, and it printed d, d and C.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140427

One very elegant way of doing this: simply use an array with the values you intend to "random" on; and then shuffle that array. And when you turn to Javas List class, you can use the built-in shuffle method:

Like:

List<Character> values = Arrays.asList('A', 'a', ... );
Collections.shuffle(values);

If you insist on using an array of char instead of that List<Character> ... you can still use the above approach, as you can easily convert that List into such an array, too (see here for example).

When not using an array, you can "flip another coin"; meaning: just get another random value, maybe 0 or 1. With 0; just keep the uppercase value; for 1, simple use the corresponding lowercase value.

(and you know you can get from 'A' to 'a' using "maths", too - similiar to what you are already doing here)

Upvotes: 1

Related Questions