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

时间:2015-12-06 16:39:36

标签: java arrays methods

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

有没有办法让我能够通过调用数组在后续方法中访问数组?或者我是否必须为每个新方法再次声明和初始化数组?

谢谢!

这是我的程序现在看起来像我的主要方法内外的数组声明。

 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复制/粘贴到这个中。

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;
    }

2 个答案:

答案 0 :(得分:0)

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

你可以:

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

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

      public static void main(String[]args) throws IOException 
      {
          ...
          HamayelSajaEmployee[] emps = ...
          ...
          listAll (emps);
      }
      

      Ans someMethod看起来像这样:

      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;
      }
      

答案 1 :(得分:0)

这与“范围”的概念有关。参加以下课程:

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”修饰符,因此我们没有对非静态变量进行静态引用。