在我的代码中,我需要从字母表中生成一个随机字母。生成字母后,需要使用draw.String方法绘制字母。我以为可以使用charAt(random)方法生成字符,但是它不起作用。我的代码在Java中。请让我知道我在做什么错以及如何解决。谢谢

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

最佳答案

我看到您的代码有两个问题。首先,您应该将生成的随机数范围限制为字母字符串的可寻址大小。其次,应该在字母字符串上调用charAt()方法,而不是将其作为独立方法。

Random rand = new Random();
int pos = rand.nextInt(alphabet.length);
String randomLetter = "" + alphabet.charAt(pos);

关于java - 生成一个随机字母并在draw.String中绘制该字母,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42287989/

10-14 13:31
查看更多