Как сделать объекты доступными для других методов? - PullRequest
0 голосов
/ 10 января 2019

Я делаю программу инвентаризации для своей школы. Я просто не понимаю этого полностью, потому что мне не хватает знаний в программировании, поэтому я обычно просто смотрю видео в YouTube. Как я могу сделать «объект arraylist» доступным для других методов ниже?

package ahaprogram2;

import java.util.Scanner;

public class AhaProgram {

    public static void main(String[] args) {
        Scanner reader = new Scanner (System.in);`
        System.out.println("Hello! This is the AHA Program of Jalosjos,             Parreno and Alfonso");
        System.out.println("Please type the letter of your option");
        boolean loop  = false;

        while (loop != true) {
            showOptions();
            inputHandler();

            String contInput = reader.nextLine();
            if (contInput.equals("1")) {
                System.out.println("Input the name of Container 1: ");
                String ContInp1 = reader.nextLine();
                Container container1 = new Container(ContInp1);
                container1.printContainer();
            } 


            if (contInput.equals("2")) {
                System.out.println("Input the name of Container 2: ");
                String ContInp2 = reader.nextLine();
                Container container2 = new Container(ContInp2);
                container2.printContainer();
            }

            if (contInput.equals("3")) {
                System.out.println("Input the name of Container 3: ");
                String ContInp3 = reader.nextLine();
                Container container3 = new Container(ContInp3);
                container3.printContainer();
            }

            if (contInput.equals("4")) {
                System.out.println("Input the name of Container 4: ");
                String ContInp4 = reader.nextLine();
                Container container4 = new Container(ContInp4);
                container4.printContainer();

             }

             if (contInput.equals("5")) {
                 System.out.println("Input the name of Container 5: ");
                 String ContInp5 = reader.nextLine();
                 Container container5 = new Container(ContInp5);
                 container5.printContainer();
             }
        }
    }

    public static void showOptions() {
        System.out.println("A = Name Containers");
        System.out.println("B = Add Cans");
        System.out.println("C = Remove Cans");
        System.out.println("D = Display Cans");
        System.out.println("E = Quit");
        System.out.println("Type a Letter: ");
    }

    public static void inputHandler() {
        Scanner reader = new Scanner(System.in);

        String input = reader.nextLine();

        if(input.equals("A")) {
             System.out.println("There are 5 containers.. What container 
          will you name? ");
             System.out.print("Type the number of your container: ");
        }

        if (input.equals("B")){
            System.out.println("Which container will you use?: ");
            System.out.print("Type a number for the container: ");
            String contforAdd = reader.nextLine();

            if (contforAdd.equals("1")) {
                System.out.println("How many cans will you add?: ");
                int numofCans1 = Integer.parseInt(reader.nextLine());

                for (int i = 0; i < numofCans1; i++) {
                    System.out.print("Enter the name of Can " + (i+1) + " : ");
                    String CanName = reader.nextLine();
                    container1.AddCan();
                }
            }
        }
    }   
}

ЗДЕСЬ ДРУГОЙ КЛАСС ДЛЯ ОБЪЕКТА И КОНСТРУКТОРОВ

import java.util.ArrayList;
import java.util.Scanner;

public class Container { 
    Scanner reader  = new Scanner(System.in);
    public ArrayList<String> CanContainer = new ArrayList<String>();
    public int Contsizep;
    public String contName;

    public Container(String contname){
        this.contName = contname;
    }

    public void AddCan(String CantoAdd) {
        this.CanContainer.add(CantoAdd);
    }

    public void printContainer() {  // for OPTION A ONLY
        System.out.println("NAME SUCCESSFUL: **" + contName +"**");
    }
}

они не могут найти символ «container1», потому что он не объявлен внутри области видимости .. Я не имею понятия объявить его за пределами

Ответы [ 3 ]

0 голосов
/ 10 января 2019

Область действия переменной представляет собой часть программы, в которой доступна определенная переменная (чтобы узнать больше об областях видимости переменных в Java, я бы рекомендовал прочитать эту статью ).

Что касается вашей непосредственной проблемы / вопроса, вы создаете переменную container1 в следующем операторе if:

if (contInput.equals("1")) {
    System.out.println("Input the name of Container 1: ");
    String ContInp1 = reader.nextLine();
    Container container1 = new Container(ContInp1);
    container1.printContainer();
}

Это означает, что область действия container1 или часть программы, в которой другие методы могут получить к ней доступ, ограничена только этим оператором if. Ваш код пытается получить доступ к container1 в функции inputHandler(), которая не только выходит за рамки container1, но и вызывается до того, как будет создан экземпляр container1. Чтобы сделать container1 доступным вне оператора if, вам придется увеличить область действия container1. Лучший способ сделать это - сделать статическую переменную экземпляра класса AhaProgram. Это будет выглядеть примерно так:

public class AhaProgram {

    private static Container container1;

    public static void main(String[] args) {
        Scanner reader = new Scanner (System.in);`
        System.out.println("Hello! This is the AHA Program of Jalosjos,             Parreno and Alfonso");
        System.out.println("Please type the letter of your option");
        boolean loop  = false;

        while (loop != true) {
            showOptions();
            inputHandler();

            String contInput = reader.nextLine();
            if (contInput.equals("1")) {
                System.out.println("Input the name of Container 1: ");
                String ContInp1 = reader.nextLine();
                container1 = new Container(ContInp1);
                container1.printContainer();
            } 

          // ...the rest of your program...
}

Надеюсь, это помогло!

0 голосов
/ 10 января 2019

Согласен с комментарием jdv. Для решения этой проблемы вы можете сделать переменную как статическое поле.

В качестве временного решения я предлагаю следующее:

import java.util.Scanner;

публичный класс AhaProgram {

private static Container container;
public static void main(String[] args) {

    Scanner reader = new Scanner (System.in);
    System.out.println("Hello! This is the AHA Program of Jalosjos,Parreno and Alfonso");
            System.out.println("Please type the letter of your option");
    boolean loop  = false;

    while (loop != true)
    {

        showOptions();
        inputHandler();
        String contInput = reader.nextLine();


        if(contInput.equals("1")) {
            System.out.println("Input the name of Container 1: ");
            String ContInp1 = reader.nextLine();
            container = new Container(ContInp1);
            container.printContainer();

        }


        if (contInput.equals("2")) {
            System.out.println("Input the name of Container 2: ");
            String ContInp2 = reader.nextLine();
            container = new Container(ContInp2);
            container.printContainer();
        }

        if (contInput.equals("3")) {
            System.out.println("Input the name of Container 3: ");
            String ContInp3 = reader.nextLine();
            container = new Container(ContInp3);
            container.printContainer();
        }

        if (contInput.equals("4")) {
            System.out.println("Input the name of Container 4: ");
            String ContInp4 = reader.nextLine();
            container = new Container(ContInp4);
            container.printContainer();

        }

        if (contInput.equals("5")) {
            System.out.println("Input the name of Container 5: ");
            String ContInp5 = reader.nextLine();
            container = new Container(ContInp5);
            container.printContainer();
        }

    }


}

public static void showOptions() {
    System.out.println("A = Name Containers");
    System.out.println("B = Add Cans");
    System.out.println("C = Remove Cans");
    System.out.println("D = Display Cans");
    System.out.println("E = Quit");
    System.out.println("Type a Letter: ");
}

public static void inputHandler() {
    Scanner reader = new Scanner(System.in);

    String input = reader.nextLine();

    if(input.equals("A")){
        System.out.println("There are 5 containers.. What container will you name? ");
                System.out.print("Type the number of your container: ");


    }

    if (input.equals("B")){
        System.out.println("Which container will you use?: ");
        System.out.print("Type a number for the container: ");
        String contforAdd = reader.nextLine();

        if (contforAdd.equals("1")) {
            System.out.println("How many cans will you add?: ");
            int numofCans1 = Integer.parseInt(reader.nextLine());

            for (int i = 0; i < numofCans1; i++) {
                System.out.print("Enter the name of Can " + (i+1) + " :");
                        String CanName = reader.nextLine();
                container.AddCan(CanName);
            }

        }

    }

}

}

Надеюсь, это поможет!

0 голосов
/ 10 января 2019

если я вас правильно понял, ответьте на ваш вопрос: Область действия вашей переменной container1 находится в условии "if" в методе "main". И эта переменная видна только внутри фигурных скобок этого условия «если». Если вы хотите установить эту переменную видимой для других методов этого класса, вам нужно сделать это полем этого класса. В вашем случае это должно быть статическое поле.

public class AhaProgram {

private static Container container1;

public static void main(String[] args) {
    Scanner reader = new Scanner (System.in);
    System.out.println("Hello! This is the AHA Program of Jalosjos,             Parreno and Alfonso");
    System.out.println("Please type the letter of your option");
    boolean loop  = false;

    while (loop != true) {
        showOptions();
        inputHandler();

        String contInput = reader.nextLine();
        if (contInput.equals("1")) {
            System.out.println("Input the name of Container 1: ");
            String ContInp1 = reader.nextLine();
            container1 = new Container(ContInp1);
            container1.printContainer();
        }
  //            ...
    }
}

}

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