Reputation:
In my code I need to generate a random letter from the alphabet. After I generate the letter I need to use the draw.String method to draw the letter. I thought I could use the method charAt(random) to generate the character but it isn't working. My code is below in java. Please let me know what i'm doing wrong and how to fix it. Thanks
Random rand = new Random();
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String randomLetter = charAt(rand);
Font letterFont = new Font( "SansSerif", Font.BOLD, 94 );
g.setFont( letterFont );
g.drawString( letter , x+45, y+100 );
Upvotes: 0
Views: 122
Reputation: 520878
I saw two problems with your code. First, you should bound the range of random numbers you generate to the addressable size of the alphabet string. Second, the charAt()
method should be called on the alphabet string, not as a standalone method.
Random rand = new Random();
int pos = rand.nextInt(alphabet.length);
String randomLetter = "" + alphabet.charAt(pos);
Upvotes: 1