所以我正致力于在Java上制作简单的刽子手游戏。 计算机应从一组单词中选择一个随机单词:
public void setWords() {
words[0] = "notions";
words[1] = "measure";
words[2] = "product";
words[3] = "foliage";
words[4] = "garbage";
words[5] = "minutes";
words[6] = "chowder";
words[7] = "recital";
words[8] = "concoct";
words[9] = "brownie";
}
我试图编写代码以在玩家玩游戏时生成随机单词:我将此作为首发:
public class Hangman {
private int numwords = 10;
private String[] words = new String[numwords];
private String gameWord;
private String dispWord = "-------";
private char[] dispArr = dispWord.toCharArray();
private static void main(String[] args) {
System.out.println("Welcome to Hangman!:");
Random rand= new Random();
char c = rand.nextChar(setWords);
}
您能否帮助使用selectGameWord()方法选择随机单词的语法? 谢谢!
答案 0 :(得分:0)
在你的主要内容中你可以选择这样的游戏单词。
String gameWord = words[rand.nextInt(words.length)];
如果你执行`.nextInt(10)&#39;,随机数的界限将是0 <= x <= 9。因为你的单词数组只有十个集合选择。
答案 1 :(得分:-1)
我相信你想从你的数组中得到一个随机的单词?您必须使用Random#nextInt()
从数组中获取随机索引。
Random random = new Random();
int index = random.nextInt(words.length);
String randomWord = words[index];
答案 2 :(得分:-2)
https://stackoverflow.com/a/5887745/6934695
你可以用这个来获取随机数。
import java.util.Random;
Random rand = new Random();
int n = rand.nextInt(words.length);
String word=selectGameWord(n)
和selectGameWord(int x);
sentence=words[x];
return sentence;
编辑:
import java.util.Random;
public class Hangman{
String words[]={"notions","measure","product","foliage"};
public String selectGameWord(int x)
{
String sentence= words[x];
return sentence;
}
public static void main (String[] args){
System.out.println("Welcome to Hangman!:");
Random rand=new Random();
Hangman myhangman= new Hangman();
int n= rand.nextInt(myhangman.words.length);
String word= myhangman.selectGameWord(n);
System.out.println(word);
}
}