简体   繁体   English

在Java中的类之间共享变量

[英]Sharing Variables between classes in Java

I have to create a maze game in my class. 我必须在课堂上创建一个迷宫游戏。 I've created the maze, but I need to share the variables from the main class to the other classes (it is a requirement). 我已经创建了迷宫,但是我需要共享从主类到其他类的变量(这是必需的)。

Here is my main code: 这是我的主要代码:

import java.io.*;
import java.util.Scanner;

public class MazeGame 
{


    public static void main(String[] args) 
    {
        getVariables();  
    }

    static void getVariables()
    {
        String fileName = "C:\\Users\\baileyjstewart\\Documents\\NetBeansProjects\\MazeGame\\src\\Maze.input";
        int size;
        int row;
        int column;
        String line = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            Scanner s = new Scanner(new File("C:\\Users\\baileyjstewart\\Documents\\NetBeansProjects\\MazeGame\\src\\Maze.input"));

            int[][] array = new int[size = s.nextInt()][size];
            for (row = 0; row < size; row++)
                {
                   for(column = 0; column < size; column++)
                   {
                       array[row][column] = s.nextInt();
                       if(array[row][column] == 0)
                       {
                           System.out.print("  ");
                           //System.out.print(array [row][column] + " ");
                       }
                       else if(array[row][column] == 1)
                       {
                           System.out.print("X "); 
                       }
                       else if(array[row][column] == 2)
                       {
                           System.out.print("E ");
                       }
                   }   
                   System.out.println(" ");
                }

            // Always close files.
            bufferedReader.close();         
        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileName + "'");                
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '");

        }

    }
}

And I'm trying to share the variables row, column, and size into my Location class: 我正在尝试将变量行,列和大小共享到我的Location类中:

import java.io.*;
import java.util.Scanner;

public class Location 
{

    MazeGame Location = new MazeGame();


    public Location()
    {
        String Wall;
        String Space;
        String Endpoint;
        Boolean Visited;
        Boolean hereNow;   
    }

    public void getVariables()
    {
        Location.getVariables();
        if(row == 0)
        {

        }

    }



}

Thank you in advance for any help. 预先感谢您的任何帮助。

public class Location 
{

MazeGame Location = new MazeGame();
....

This wont work because the class name is exactly the same as the variable name. 这不会起作用,因为类名与变量名完全相同。

Also, your Location class is never used because the program entry point ( main function ) is declared in the MazeGame class. 另外,从不使用您的Location类,因为在MazeGame类中声明了程序入口点(main函数)。

I wrote another answer elsewhere that goes into explaining constructors, classes, and setters/getters that you may want to read. 我在其他地方写了另一个答案 ,解释了您可能想阅读的构造函数,类和设置器/获取器。

Let me know if you need more examples or if you still don't understand. 让我知道您是否需要更多示例,或者仍然不了解。

As others have pointed out, the class name 'Location' is same as the variable (object) name. 正如其他人指出的那样,类名“ Location”与变量(对象)名相同。 You need to read about OOP rules and principles. 您需要阅读有关OOP规则和原则的信息。

One way you to share variables across classes will be to declare the variable as 'static'. 跨类共享变量的一种方法是将变量声明为“静态”。 Please remember that 'static' variables are not encouraged and they are considered as evil. 请记住,不鼓励使用“静态”变量,它们被认为是邪恶的。

Still, if you would like to see how your code can share variables across classes, here is your code with some changes (though this is NOT perfect). 不过,如果您希望了解代码如何在类之间共享变量,请在此处进行一些更改(尽管这并不完美)。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MazeGame 
{

    protected static int row;

    public static void main(String[] args) throws IOException 
    {
        getVariables();  
    }

    public int getRow() {
        return MazeGame.row;
    }

    static void getVariables() throws IOException
    {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        System.out.println("Enter a value for row : ");
        String strRow = br.readLine();
        MazeGame.row = Integer.parseInt(strRow);

        Location ln = new Location();
        ln.getVariables();
    }
}


import java.io.IOException;

public class Location 
{

     MazeGame Locationx = new MazeGame();

    public Location()
    {

    }

    public void getVariables() throws IOException
    {
         System.out.println("The value of class variable row, initially is: "+MazeGame.row); // class variable

         Locationx.row = 21; // object variable
         System.out.println("The value of object variable row, after modification is: "+Locationx.row);

         MazeGame.row = 23; // class variable
         System.out.println("The value of class variable row, after modification is: "+MazeGame.row);
     }
}

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

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