首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在main中声明的数组不能在后续方法中访问- Java

在main中声明的数组不能在后续方法中访问- Java
EN

Stack Overflow用户
提问于 2015-12-07 00:39:36
回答 2查看 52关注 0票数 0

我在main方法中声明并初始化了一个数组。我无法在同一程序中的任何后续方法中访问该数组。这正常吗?

有没有办法让我在后续的方法中只需调用数组就能访问该数组?或者,我是否必须为每个新方法重新声明和初始化数组?

谢谢!

这就是我的程序现在的样子,在main方法内部和外部都有数组声明。

代码语言:javascript
复制
 import java.io.*; 
 import java.util.*; 

public class useHamayelSajaEmployee 
{
    final int MAX_EMPLOYEES = 1000;
    HamayelSajaEmployee []emps = new HamayelSajaEmployee[MAX_EMPLOYEES]; 

    public static void main(String[]args) throws IOException 
    {
        Scanner scan = new Scanner(System.in); //scanner for reading from keyboard

        final int MAX_EMPLOYEES = 1000;
        HamayelSajaEmployee []emps = new HamayelSajaEmployee[MAX_EMPLOYEES]; 

        File file = new File("empList.txt");
        Scanner scan2 = new Scanner(file); //scanner for reading from file

        String divisionTitle = scan2.nextLine(); 
        int numOfEmps;

        for (int k = 0; k < 1000; k++) //for loop to set all the objects in array to constructor values
                    {
                        emps [k] = new HamayelSajaEmployee();
                    }

        int lastCount = 0; 

            while(!divisionTitle.equals("END_OF_FILE"))
        {
            System.out.println(divisionTitle + '\n');
            numOfEmps = scan2.nextInt();

            for (int i = lastCount; i < numOfEmps + lastCount; i++) //instead of starting from the 0 point and writing over the objects in array, starting from point we stopped with lastCount
            {
                HamayelSajaEmployee emp1 = new HamayelSajaEmployee();

                emp1.SetDivisionTitle(divisionTitle);

                String lastName = scan2.next();
                System.out.print(lastName + "\t" ); 
                emp1.SetLastName(lastName);

                String firstName = scan2.next();
                System.out.print(firstName + "\t");
                emp1.SetFirstName(firstName);

                int yearsInCompany = scan2.nextInt();
                System.out.print(yearsInCompany + "\t" );
                emp1.SetYearsInCompany(yearsInCompany);

                double salary = scan2.nextDouble();
                System.out.print(salary + "\t"  + "\t" );
                emp1.SetSalary(salary);

                String status = scan2.next();
                char status1 = status.charAt(0);
                System.out.print(status1 + "\t" );
                emp1.SetStatus(status1);

                String section = scan2.nextLine();
                System.out.println(section);
                emp1.SetSection(section);


                emps [i]= emp1;

            }
            System.out.println('\n'); //prints extra line between divisions for clarity
            divisionTitle = scan2.next();
            lastCount = numOfEmps + lastCount;
        }

        for (int i = 0; i < 1000; i++)
        { 
            if(!emps[i].GetDivisionTitle().equals("noDivsionTitle"))//so that no empty slots in array print
            {System.out.println(emps[i]);}
        }


        System.out.print("Enter 'M' to go to the Menu or 'Q' to Quit");
        String newPlace = scan.next();
        char newPlace1 = newPlace.charAt(0);


        if(newPlace1 == 'M' || newPlace1 == 'm')
        {menu();}

        if (newPlace1 == 'Q' || newPlace1 == 'q')
        {finalStats();}

        else
            {
            while (!(newPlace1 == 'M' || newPlace1 == 'm' || newPlace1 == 'Q' || newPlace1 == 'q'))
                {
            System.out.println("ERROR");
            System.out.println("Please try again.");

            System.out.print("Enter 'M' to go to the Menu or 'Q' to Quit");
            newPlace = scan.next();
            newPlace1 = newPlace.charAt(0);
            if(newPlace1 == 'M' || newPlace1 == 'm')
            {menu();}

            if (newPlace1 == 'Q' || newPlace1 == 'q')
            {finalStats();}
                }
            }

    }

这是另一个方法的样子(我直接将初始化和数组声明从main复制/粘贴到这个方法中。

代码语言:javascript
复制
public static boolean listAll()
    {
        /* method meant to list all the employees names, years in company, salaries, statuses, and sections as read in from file*/
        File file = new File("empList.txt");
        Scanner scann = new Scanner(file);

        String divisionTitle = scann.nextLine(); 
        int numOfEmps;

        final int MAX_EMPLOYEES = 1000;
        HamayelSajaEmployee []emps = new HamayelSajaEmployee[MAX_EMPLOYEES]; 

        for (int k = 0; k < 1000; k++) //for loop to set all the objects in array to constructor values
                    {
                        emps [k] = new HamayelSajaEmployee();
                    }

        int lastCount = 0; 

            while(!divisionTitle.equals("END_OF_FILE"))
        {
            System.out.println(divisionTitle + '\n');
            numOfEmps = scann.nextInt();

            for (int i = lastCount; i < numOfEmps + lastCount; i++) //instead of starting from the 0 point and writing over the objects in array, starting from point we stopped with lastCount
            {
                HamayelSajaEmployee emp1 = new HamayelSajaEmployee();

                emp1.SetDivisionTitle(divisionTitle);

                String lastName = scann.next();
                System.out.print(lastName + "\t" ); 
                emp1.SetLastName(lastName);

                String firstName = scann.next();
                System.out.print(firstName + "\t");
                emp1.SetFirstName(firstName);

                int yearsInCompany = scann.nextInt();
                System.out.print(yearsInCompany + "\t" );
                emp1.SetYearsInCompany(yearsInCompany);

                double salary = scann.nextDouble();
                System.out.print(salary + "\t"  + "\t" );
                emp1.SetSalary(salary);

                String status = scann.next();
                char status1 = status.charAt(0);
                System.out.print(status1 + "\t" );
                emp1.SetStatus(status1);

                String section = scann.nextLine();
                System.out.println(section);
                emp1.SetSection(section);

                emps [i]= emp1;

            }
            System.out.println('\n'); //prints extra line between divisions for clarity
            divisionTitle = scann.next();
            lastCount = numOfEmps + lastCount;
        }

        for (int i = 0; i < 1000; i++)
        { 
            if(!emps[i].GetDivisionTitle().equals("noDivsionTitle"))//so that no empty slots in array print
            {System.out.println(emps[i]);}
        }

        return true;
    }
EN

回答 2

Stack Overflow用户

发布于 2015-12-07 00:41:58

在方法(如main方法)中本地声明的数组只能在该方法中访问。

您可以执行以下任一操作:

  1. 使数组成为您的类的实例或类成员,这将允许您的类的其他方法访问它。

  1. 将其作为参数传递给任何需要它的方法。

要将数组作为参数传递,请执行以下操作:

代码语言:javascript
复制
public static void main(String[]args) throws IOException 
{
    ...
    HamayelSajaEmployee[] emps = ...
    ...
    listAll (emps);
}

Ans someMethod将如下所示:

代码语言:javascript
复制
public static boolean listAll (HamayelSajaEmployee[] emps)
{
    for (int i = 0; i < emps.length; i++) { 
        if(!emps[i].GetDivisionTitle().equals("noDivsionTitle")) {
            System.out.println(emps[i]);
        }
    }

    return true;
}
票数 0
EN

Stack Overflow用户

发布于 2015-12-07 00:47:15

这与“作用域”的概念有关。以以下类为例:

代码语言:javascript
复制
public class SomeClass {
    int x = 3;
    public void SomeMethod() {
        int y = 5;
        if(x != y) {
            int z = x + y;
        }
    }
}

"x“可以在SomeClass中的任何地方访问,y只能在SomeMethod中访问,z只能在if语句中访问。这样想:当你声明一个变量时,它只能在它周围最紧凑的两个{}中访问。这是作用域概念的基础。现在,一旦你开始使用不同的变量修饰符(比如"public"),你就可以开始改变给定变量/方法的作用域。

为了解决不能在另一个方法中访问在一个方法中创建的数组的问题,我建议类似于"x“在我的示例类中的位置来声明该数组。然后在整个类中都可以访问它。

如果您感兴趣,在Oracle的网站上有一篇关于访问控制和修饰符的文章,但对于这个特定的问题,这篇文章并不是必需的:https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

编辑:删除了SomeMethod的" static“修饰符,这样我们就不会对非静态变量进行静态引用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34119908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档