2015-02-23 84 views
-1

我有我的代码,但我不能让我的变量棒()或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

创建像静态类:

static class MyParameters { 
    int stick; 
    int scrapMetal; 
    MyParameters(int stick, int scrapMetal) { 
     //set variables 
    } 
    //getters 
} 
从你的方法

现在turnOne你可以只返回使用getter像MyParameters(而不是无效)并获得两个值的实例:

MyParameters parameters = turnOne(); 
System.out.println(parameters.get...); 
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... 
} 
相关问题