简体   繁体   English

如何在2个不同的类上使用一个数组

[英]How to use one array on 2 different classes

I have 2 classes right now, the first class has the arraylist in it. 我现在有2个班级,第一个班级中有arraylist。 But on the second class when I try to access the arraylist it keeps giving me the red line underneath saying that the variable doesn't exist. 但是在第二个类中,当我尝试访问arraylist时,它始终在下面显示红线,表明该变量不存在。

Here is class one... 这是第一课...

public class BankMain {


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BankMain main = new BankMain();

        menu();
    }

    public static void cardNumbers(){
        ArrayList<Integer> cardNum = new ArrayList<Integer>();
        Scanner cards = new Scanner(System.in);
        Scanner input = new Scanner(System.in);
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please select a 5 digit card number");

        cardNum.add(input.nextInt());

        System.out.println("Thank you! You're card number is " +cardNum);

        System.out.println("Type 'c' to go back to main menu.");
        String value  = keyboard.next();
        if(value.equalsIgnoreCase("c")){
            menu();
        }
        else if (!keyboard.equals('c')){
            System.out.println("Invalid Entry!");
        }
    }

    public static void menu(){
        System.out.println("What Would you like to do today?");
        System.out.println();
        System.out.println("Create Account = 1");
        System.out.println("Login = 2");
        System.out.println("Exit = 3");
        query();
    }

    public static void query(){
        Scanner keyboard = new Scanner(System.in);
        double input = keyboard.nextInt();  

        if (input == 2){
            BankMainPart2 main2 = new BankMainPart2();
            System.out.println("Please enter your 5 digit card number.");
            main2.loginCard();
        }
        else if (input == 1){
            cardNumbers();
        }
        else if (input == 3){
            System.out.println("Thank you, have a nice day!");
            System.exit(0);
        }
    }
}

Here is the second class... 这是第二节课...

public class BankMainPart2 {
    public static void loginCard(){
        if (cardNum.contains(name)) {
        }
    }
}

I know I haven't entered anything in the if statement yet on the second class but I'm just trying to get my array list to work on both classes. 我知道我还没有在第二个类的if语句中输入任何内容,但是我只是想让我的数组列表在两个类上都可以使用。

The code looks very naive. 该代码看起来很幼稚。 A very simple answer to your question is 一个简单的答案是

You have not declared any cardNum in BankMainPart2 as global variable or in loginCard as local variable, how do you think it will be available in the loginCard method? 您尚未在BankMainPart2中将任何cardNum声明为全局变量或在loginCard中将其声明为局部变量,您认为如何在loginCard方法中将其可用?

ArrayList<Integer> cardNum = new ArrayList<Integer>();

is local to cardNumbers method. 对cardNumbers方法而言是本地的。

How can you access it from other class? 您如何从其他班级访问它?

  1. A local variable cannot be accessed from outside the method, so first thing, make cardNum class level variable 无法从方法外部访问局部变量,因此首先使cardNum类级别变量
  2. Make the variable public if you want other classes to be able to access it directly, else make the variable private and create getter method (setter if required). 如果希望其他类能够直接访问该变量,则将其设置为public,否则将其设置为private并创建getter方法(如果需要,可以设置为setter)。
  3. You can also send the variable when calling the method as argument 您也可以在调用方法作为参数时发送变量
  4. If this is class level variable, make it static and use Classname.variable. 如果这是类级别的变量,则使其为静态并使用Classname.variable。

--Edit-- - 编辑 -

As you have asked for details let me give you a quick overview of the different approaches. 当您要求提供详细信息时,让我为您简要介绍不同的方法。

  1. A variable declared inside a method is local. 在方法内部声明的变量是局部变量。 as name suggest "local", no one but the method knows there is such a variable. 顾名思义,该变量是“ local”,但除了方法之外,没人知道存在这样的变量。 No other method in the class knows about existence of this variable, let alone some outside class. 该类中没有其他方法知道此变量的存在,更不用说一些外部类了。
  2. I say you can make it static, but static should strictly be used for class level storage, not object level. 我说可以将其设置为静态,但必须严格将静态用于类级别的存储,而不是对象级别。 Say a list which is modified by multiple objects of the same class (I hope you know concepts of objects, else go to the basics otherwise it will not be clear). 说一个被同一类的多个对象修改的列表(我希望您了解对象的概念,否则请参阅基础知识,否则将不清楚)。 Now as per your example, I guess this is not what you want. 现在按照您的示例,我想这不是您想要的。
  3. A public variable is generally no - no, only in few cases it will be useful (for example in android programming where performance is utmost important). 公共变量通常不是-否,只有在少数情况下才有用(例如,在性能最重要的android编程中)。 Normally we will create a variable and provide getter setters. 通常,我们将创建一个变量并提供getter setter。 A getter or setter is used normally when we want to give access to the variable, which again does not look like what you want. 当我们想要访问变量时,通常会使用getter或setter,但这又看起来并不像您想要的那样。
  4. Last, the variable is private to you class, but if you want some method to do something about it, you can pass it as argument, this looks the case for you. 最后,该变量对您的类而言是私有的,但是如果您想要某种方法对其进行某些操作,则可以将其作为参数传递,这对您而言似乎是正确的。

Step by step 一步步

take the variable out of method and add to class level, note that I removed static from method names 将变量移出方法并添加到类级别,请注意,我从方法名称中删除了static

public class BankMain {
private ArrayList<Integer> cardNum = new ArrayList<Integer>();
// rest of code as it is 
..
..
 BankMain main = new BankMain();
 //change
    main.menu();

 //no need foe static
  public void cardNumbers(){
//no need here now        
//ArrayList<Integer> cardNum = new ArrayList<Integer>();
        Scanner cards = new Scanner(System.in);
        Scanner input = new Scanner(System.in);
..
..

//public static void menu(){
  public void menu(){


//send the list
 //I see there are confusion at times regarding calling of static method.
 //please note objectname.staticMethod() or classname.staticMethod() is one 
 //and same thing. Just that classname.staticMethod() is more clear 
 BankMainPart2.loginCard(cardNum);

}

and

public class BankMainPart2 {
    public static void loginCard(ArrayList<Integer> cardNum){
        if (cardNum.contains(name)) {
        }
    }
}

Your method, BankMainPart2.loginCard has not context of "cardNum", it doesn't know what it is (type or value). 您的方法BankMainPart2.loginCard没有“ cardNum”的上下文,它不知道它是什么(类型或值)。

In order for the method to be able to act on the array list, you must pass a reference to it, something like... 为了使该方法能够作用于数组列表,您必须传递对其的引用,例如...

public class BankMainPart2 {
    public static void loginCard(ArrayList<Integer> cardNum){
        if (cardNum.contains(name)) {
        }
    }
}

make the cardnum arraylist as an instance variable in BankMain class and extend BankMain in BankMainClass2 and using reference of BankMain you would be able to access cardNum like this 使cardnum arraylist作为BankMain类中的实例变量并在BankMainClass2中扩展BankMain,并使用BankMain的引用,您将能够像这样访问cardNum

Class BankMain {
  public ArrayList<String> cardNum = new ArrayList<String>();

 }
 Class BankMain2 extends BankMain {
    public void method() {
  BankMain2 main = new BankMain2();
      sysout(main.cardNum.size());
      }
 }

but the above scenario would only work when cardNum ArrayList in BankMain class is either marked public,protected or default(Nomodifier). 但是上述情况仅在BankMain类中的cardNum ArrayList标记为public,protected或default(Nomodifier)时才有效。 it wouldnt work if its marked as private and other non access modifier such as static and final 如果将其标记为私有和其他非访问修饰符(例如静态和最终),它将无法正常工作

You can try any one of these 您可以尝试任何一种

1.Declare the Arraylist as public then import the first class and use the cardNum in the second class 1.将Arraylist声明为public,然后导入第一类并在第二类中使用cardNum

2.Make the cardNum a static var and use it directly in second class as BankMain.cardNum 2.使cardNum为静态变量,并在第二类中将其直接用作BankMain.cardNum

3.Pass the Arraylist as argument to the second class. 3.将Arraylist作为参数传递给第二个类。

The key problem is in the the way you are trying to create your classes. 关键问题在于您尝试创建类的方式。 Your current problem can be solved by answer given by @MadProgrammer. 您当前的问题可以通过@MadProgrammer给出的答案来解决。 But you should definitly have a look into the Object Oriented Programming Concepts. 但是,您应该明确了解面向对象的编程概念。 This section on How to identify and design a Class? 本节介绍How to identify and design a Class? should give you some clear pointers. 应该给您一些明确的指示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM