我正在用java写一个刽子手游戏,我遇到了一个问题。我有一个方法,从数组中选择一个随机字并将其存储在一个变量中。现在在游戏运行的方法中,我将如何使用随机字变量?
public class Hangman {
public static Scanner qwe = new Scanner(in);
public static void word(){
String words[]= {"Cat","dog"};
int i = words.length;
Random rng = new Random();
int choice = rng.nextInt(words.length); //Varible storing random word
gameStart();
}
public static void gameStart(){ //Asks user if they wish to start
out.println("Welcome to my hangman game!");
out.println("Would you like to begin?");
String asd = qwe.nextLine().toLowerCase();
if (asd.contains("y")){
game();
}
else if (asd.contains("n")){
exit(0);
}
else{
out.println("Not a recognized answer");
gameStart();
}
}
public static void game(){
out.println(choice); //Trying to print out random word varible
}
public static void main(String[] args) {
out.println("HangMan Game made by Ryan Hosford\n");
gameStart();
}
}
答案 0 :(得分:2)
您不能直接在其他method variables
中使用methods
,因为它们local
method
。
您可以将它们传递给该方法。或者将该方法设置为return
所需的value
并在您想要的地方打电话。
您无法使用word()
方法。您可以返回value
public static int word(){
String words[]= {"Cat","dog"};
int i = words.length;
Random rng = new Random();
int choice = rng.nextInt(words.length); //Varible storing random word
return choice;
}
然后,在game()
方法
public static void game(){ //Asks user if they wish to start
int choice= word(); <-- call word that gives you choice
// so now you have choice here. you can use it now.
out.println(choice);
}
答案 1 :(得分:0)
在函数内声明变量时,它是该函数的本地变量。如果你想允许访问变量,你必须基本上声明它,使得该上下文中的每个函数都能够访问它。您可以使用嵌套调用将变量作为函数参数传递,也可以使用访问修饰符(例如static
)声明变量。
BY通过将words[]= {"Cat","dog"}
方法签名更改为gameStart()
来使gameStart(String word)
静态并使用所选单词调用gameStart(String word):
public static String words[]= {"Cat","dog"};
public static int word(){
int i = words.length;
Random rng = new Random();
int choice = rng.nextInt(words.length); //Varible storing random word
gameStart(words[choice]);
}
public static void gameStart(String chosenWord){
//......... your code
if (asd.contains("y")){
game(chosenWord);
}
//....... your code
}
public static void game(String chosenWord)
{
System.out.println(chosenWord);
}
或,添加静态字符串chosenWord
,如下所示:
public static String chosenWord = ""; // using a static variable chosenWord
public static String words[]= {"Cat","dog"};
public static void word(){
int i = words.length;
Random rng = new Random();
int choice = rng.nextInt(words.length); //Varible storing random word
chosenWord = words[choice] ; // chosen word assigning
gameStart();
}
public static void game()
{
System.out.println(chosenWord);
}
答案 2 :(得分:0)
word()
方法中的所有变量都是局部变量,它们的范围仅在它们声明的方法中。
为了延长选择的寿命,请创建一个字段(为方便起见静态):
static String word;
public static void word(){
...
word = words[rng.nextInt(words.length)];
然后word
字段(变量)对另一种方法中的代码可见。