2015-02-23 44 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... 
} 
相關問題