简体   繁体   English

如何在另一种方法中使用已经创建的 object?

[英]How do I use an already created object in one method in another?

Alright so i created an instance of Game called game1 but how do I go about using the same instance of game1 in other methods?好吧,所以我创建了一个名为 game1 的 Game 实例,但是我如何 go 关于在其他方法中使用相同的 game1 实例? This is what I have so far这是我到目前为止所拥有的

public static void main(String[] args) {公共 static 无效主(字符串 [] 参数){

    int[] lotto1 = {3,11,15,27};
    int[] lotto2 = {11,14,18,21};
    int[] lotto3 = {9,22,29,30};
    int[] lotto4 = {1,7,13,22};
    int[] lotto5 = {11,21,22,30};
    ArrayList<Ticket> participants = new ArrayList<>();

    participants.add(new Ticket("Santos", "Dundalk", 899795253,lotto1));
    participants.add(new Ticket("Temi", "Balbriggan", 899795253, lotto2));
    participants.add(new Ticket("Miracle", "Dundalk", 899795253, lotto3));
    participants.add(new Ticket("Lateef", "Dublin", 899795253, lotto4));
    participants.add(new Ticket("Elijah", "Dundalk", 899795253, lotto5));

    Game game1 = new Game(participants);


}
public static void DisplayAllTickets()
{
    game1.displayAllTickets();
}

This is my Display all method in my Game class这是我在我的游戏 class 中显示所有方法

 public void displayAllTickets()
    {
        for (int i = 0; i < ticket.size(); i++)
        {
            System.out.println(ticket.get(i));
        }
    }

If you want to use the game1 object in other functions you could hand it to your function as a parameter.如果您想在其他功能中使用game1 object,您可以将其作为参数交给您的function。

public static void exampleFunction(Game game){
  //your function body where you do fancy stuff with your object
}

PS附言

You can invoke the displayAllTickets() function directly on your game1 object without adapter function DisplayAllTickets() .您可以直接在您的game1 1 object 上调用displayAllTickets() function ,无需适配器 function DisplayAllTickets()

game1.displayAllTickets();

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

相关问题 如何创建已存在于另一种方法中的新对象? - How do I create a new object that already exists in another method? 如何从另一个类方法调用已创建对象的方法? - How to call a method of an already created object from another class method? 如何在Java中将在一个类中创建的对象传递给另一个类? - How do I pass an object created in one class to another in java? 如何在一种方法中将变量用于另一种方法? - How do I use variables in one method into another method? 如何在另一方法的方程式中的一种方法中使用变量? - How do I use variables in one method in an equation in another method? 用户创建了堆后,如何使用HeapSort方法? - How do I use the HeapSort Method after the user has already created the Heap? 如何在另一种方法中使用一种方法中的变量? - How do I use a variable from one method oin another? 我如何正确调用我创建的方法,以便我能够在另一个中使用它? - How do i properly call the method that I created so that I'm able to use it within another? 如何在方法中使用另一种方法? - How do I use another method in a method? 如何在不声明另一个 Scanner 对象的情况下在已扫描的字符串上使用分隔符? - How do I use a delimiter on an already-scanned String without declaring another Scanner object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM