Как получить доступ к записи из другой процедуры? - PullRequest
0 голосов
/ 02 октября 2019

Поэтому у меня возникла проблема, когда я хотел бы создать запись в одной процедуре, а затем изменить атрибуты этой записи, используя другие процедуры и функции.

  import java.util.Scanner; // Imports scanner utility
  import java.util.Random;
  import java.lang.Math;

  class alienPet
  {
      public void main (String[] param)
      {
          // We want to call all of the functions
          // and procedures to make an interactive
          // alien program for the user.

          welcomeMessage();
          alienCreation();

          System.exit(0);

      } // END main

        /* ***************************************
        *   Define a method to obtain the users input
        * and start the correct method.
        */

        public static String userInput (String message)
        {
          Scanner scan = new Scanner(System.in);
          String inp;
          print(message);
          inp = scan.nextLine();
              return inp;
        } // END userInput

        /* ***************************************
      * Define a method to print messages.
      */

      public static void print (String message)
      {
          System.out.println(message);
          return;
      } // END print

      /* ***************************************
      * Define a method to 
      */

      public static void welcomeMessage ()
      {
        print("Thank you for playing the pet alien game");
        print("In this game, you will have to look after your own alien.");
        print("There is multiple aspects to looking after your alien, such as:");
        print("Hunger, Behaviour and Thirst."); 
        print("");
        print("When prompted, you can use the following commands:");
        print("feed -> Replenishes alien to max hunger level");
        print("drink -> Replenished thirst level to max");
        print("");
          return;
      } // END 


      /* ***************************************
      * Define a method to 
      */

      public void alienCreation ()
      {
        Alien ufo = new Alien();
        ufo.name = userInput("What would you like to name your new alien?");
        ufo.hungerRate = ranNum(1, 6);
        print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
        alienBehaviour(ufo.hungerRate);
          return;
      } // END alienCreation

      public void alienBehaviour (int hunger) {
          if (hunger <= 2){
              print(ufo.name + " is very hungry, and is dangerously angry!!");
              String action = userInput("You should feed it as soon as possible. (by typing 'feed')");
              if (action.equals("feed")){
                  feedAlien();
              }else if (action.equals("drink")) {
                  alienDrink();
              }else{
                  print("That is a dangerous decision.");
              }
          }else if (hunger <= 4) {
            print(ufo.name + " is mildly hungry, but is in a calm state.");
              String action = userInput("Would you like to take any actions?");
              if (action.equals("feed")){
                  feedAlien();
              }else if (action.equals("drink")) {
                  alienDrink();
              }else{
                  print("Okay.");
              }
          }else if (hunger <= 6) {
            print(ufo.name + " is not hungry and is in a happy state.");
              String action = userInput("Would you like to take any actions?");
              if (action.equals("feed")){
                  feedAlien();
              }else if (action.equals("drink")) {
                  alienDrink();
              }else{
                  print("Okay.");
              }
          }
      }

      public void feedAlien() {
          ufo.hungerRate = 6;
          print(ufo.name + "'s hunger level replenished to max level 6.");
          print(ufo.name + " is now at a happy level.");
      }

      public void alienDrink() {
        ufo.thirst = 6;
        print(ufo.name + "'s thirst level replenished to max level 6.");
    }

      public static int ranNum(int min, int max){ // A function that generates a random integer wihin a given range.
        Random random = new Random();
        return random.ints(min,(max+1)).findFirst().getAsInt();
    } // END ranNum

  } // END class alienPet

  class Alien {
      String name;
      int age = 0;
      int hungerRate;
      int thirst = 6;
  }

Очевидно, что некоторые из аннотацийнеполной на данный момент, но у меня проблема в процедурах alienBehaviour (), feedAlien () и alienDrink (), я не могу получить доступ к записи, созданной в процедуре alienCreation (). Все ошибки одинаковы и выглядят следующим образом:

alienPet.java:84: error: cannot find symbol
              print(ufo.name + " is very hungry, and is dangerously angry!!");
                    ^
  symbol:   variable ufo
  location: class alienPet

Теперь я новичок в Java, поэтому я не уверен, должен ли я сделать запись глобальной или что-то еще, поэтому любая помощь будет оченьоценили.

Ответы [ 2 ]

1 голос
/ 02 октября 2019

У вас проблемы с областью действия вашей переменной. Переменные действительны только в фигурных скобках, в которых они были объявлены.

НЕПРАВИЛЬНО

public void alienCreation ()
{
    Alien ufo = new Alien();
    ufo.name = userInput("What would you like to name your new alien?");
    ufo.hungerRate = ranNum(1, 6);
    print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
    alienBehaviour(ufo.hungerRate);
    return;
} // END alienCreation and of the scope of your variable ufo

ПРАВО

class alienPet
{
    Alien ufo;
    [...]
    public void alienCreation ()
    {
        ufo = new Alien();
        ufo.name = userInput("What would you like to name your new alien?");
        ufo.hungerRate = ranNum(1, 6);
        print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
        alienBehaviour(ufo.hungerRate);
        return;
    } // END alienCreation and your variable ufo will be initialized afterwards
}
1 голос
/ 02 октября 2019

Переменные, объявленные внутри метода, называются local переменными и, вероятно, удаляются, когда метод завершает выполнение.

Переменные, объявленные вне какой-либо функции, называются instance переменными, и к ним можно получить доступ (используется) на любую функцию в программе.

Вы ищете переменную экземпляра Alien ufo.

class alienPet{ // It is recommended you use the java naming convention.
    Alien myAlien = new Alien();
    // alienPet a = new alienPet();
    // a.myAlien; // you could potentially do this to get an alien from an alienPet class
    void someVoid(){
        Alien otherAlien;
    }
    void errorVoid(){
        otherAlien.toString(); 
// causes an error, the otherAlien variable is never visible to errorVoid as it is a local variable
        myAlien.toString(); // OK
    }
}

https://www.oracle.com/technetwork/java/codeconventions-135099.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...