我有我的代码,但我不能让我的变量stick()或scrapMetal()继续。它的设置是为了给你一个随机数量,但我只能重新计算一个值。我该怎么办?我尝试在方法之外声明变量,但那也没有用! 代码:
public void turnOne(){
System.out.println();
System.out.println();
System.out.println();
System.out.println("You realise that in order to survive, you must leave the planet.");
System.out.println("You start to look around, thinking of how you could repair your ship.");
System.out.println("<Press 1 to scavenge, 2 to move north, 3 for east, 4 for south, or 5 for west>");
System.out.println();
System.out.println();
System.out.println();
Scanner input = new Scanner(System.in);
int yesno = input.nextInt();
int drops = ((int)(Math.random() * 5));
int stick = 0;
int scrapMetal = 0;
if (yesno == 1){
System.out.println("You start to scavenge your surroundings.");
if (drops == 4){
System.out.println("You found sticks!");
stick = ((int)(Math.random() * 6));;
System.out.println("You now have " + stick + " sticks!");
}
else{
System.out.println("You were not able to find any sticks.");
}
drops = ((int)(Math.random() * 9));
if (drops == 7){
System.out.println("You found some scrap metal!");
scrapMetal = ((int)(Math.random() * 4));
System.out.println("You now have " + scrapMetal + " pieces of scrap metal!");
}
else{
System.out.println("You were not able to find any scrap metal.");
}
System.out.println("What would you like to do now?");
}
}
答案 0 :(得分:0)
创建静态类,如:
static class MyParameters {
int stick;
int scrapMetal;
MyParameters(int stick, int scrapMetal) {
//set variables
}
//getters
}
现在从你的方法turnOne
你可以返回一个MyParameters实例(而不是void)并使用getter访问这两个值,如:
MyParameters parameters = turnOne();
System.out.println(parameters.get...);
答案 1 :(得分:0)
对于要在多个方法之间共享的变量,变量'stick'和'scrapMetal'应该在这些方法之外编码,但在类中包含这些方法。
实施例: -
public class YourProgram
{
int stick;
int scrapMetal;
//Maybe Some constructors here...
public void turnOne()
{
//DO NOT declare variables stick and scrapMetal here again.
//Your above code goes here....
}
public void someOtherMethod()
{
//DO NOT declare variables stick and scrapMetal here again.
//Some code goes here which uses stick and/or scrapMetal variables...
}
//Probably some more methods and other code blocks go here...
}