簡體   English   中英

如何從靜態方法輕松訪問類的各種實例中的變量

[英]How to easily access variables in various instances of classes from static methods

我一直在進行紙牌游戲Gin Rummy的基本模擬,盡管目前尚不完善 ,但它能夠運行一副紙牌的基本功能,直到我嘗試實現一種對每只紙牌發牌的方法為止播放器。

Player類應該由一個ArrayList (在每個玩家手中持有卡牌)和一個integer (用作玩家ID)組成。 我已經將它們聲明為static對象,但是當然這意味着我現在創建的Player每個實例都具有相同的Handplayerid因為變量是靜態的。

那就是我面臨的問題。 我帶領相信任何static類或方法,只能訪問其他static類,方法等的對象作為main方法必須是static ,當然任何事情它可以訪問有也是static等等等等? 我的Player類中的對象如何不能是靜態的,從而允許我為Player的每個實例分配不同的Handplayerid

我已經在下面包含了我的代碼,很抱歉,我已經很久了,以為以防萬一。 為了記錄PlayGinRummy ,正是在PlayGinRummy類中,我調用Player新實例PlayGinRummy錯誤non-static variable Hand cannot be referenced from a static context

package labexercise1;

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class DeckOfCardsTest {

public DeckOfCardsTest(){}

private static int Menu;

public static void main(String[] args) throws InterruptedException{

    DeckOfCards.FillDeck(); 

    do{
        Thread.sleep(1000);
        System.out.println("Please select from the following menu options using the corresponding number:");
        System.out.println("1. Display Deck | 2. Shuffle Deck | 3. Cut Deck | 4. Start Game | 5. Exit"); //Start game will lead into another switch menu to set no of players etc.
        System.out.print("Your choice: ");
        Scanner UserInput = new Scanner(System.in);
        System.out.println();
        Menu = UserInput.nextInt(); // Maybe build in a system that recognises, for example, "1", "one" and "One" as the menu selection 1, using if/else
        System.out.println();

        switch(Menu){
            case 1:
                DeckOfCards.DisplayDeck();
                break;

            case 2:
                DeckOfCards.ShuffleDeck();
                break;

            case 3:
                DeckOfCards.CutDeck();
                break;

            case 4:
                PlayGinRummy.DealDeck(); // Maybe shuffle things around so this just calls a method in player, from which everything else is called. Would mean moving things over from DeckOfCards so Player had access to hp, cp1, cp2 and cp3.
                break;

            case 5: 
                System.out.println("The program will now end.");
                System.out.println();
                break;

            default: 
                System.out.println("Your input is not a valid selection.");
                System.out.println();
                break;
        }
    } while(Menu!=5);
}

public class DeckOfCards {

    public DeckOfCards(){}

    public static ArrayList<Integer> Deck = new ArrayList<>(); 
    public static ArrayList<Integer> Discard = new ArrayList<>();

    public static void FillDeck() throws InterruptedException{
        System.out.print("Compiling deck");
        DeckOfCards.CountdownEffect();
        for(int count=0; count<52; count++){
            Deck.add(count);
        }
        System.out.println(" Deck compiled!");
        System.out.println();
    }   

    public static void DisplayDeck() throws InterruptedException{
        System.out.println("Displaying deck contents:");
        Thread.sleep(1000);
        for(int count=0; count<52; count++){
            System.out.println(Deck.get(count));
        }
        System.out.println();
    }

    public static void ShuffleDeck() throws InterruptedException{
        System.out.print("Shuffling deck");
        Thread.sleep(1000);
        for(int count=0; count<3; count++){
            System.out.print(".");
            Thread.sleep(1000);
        }
        Collections.shuffle(Deck);
        System.out.println(" Deck shuffled!");
        System.out.println();
    }

    public static void CutDeck() throws InterruptedException{
        System.out.print("Cutting deck");
        Thread.sleep(1000);
        for(int count=0; count<3; count++){
            System.out.print(".");
            Thread.sleep(1000);
        }
        System.out.println();
        System.out.println("The cut card is:");
        Random random = new Random();
        int CutPoint = 51 - (random.nextInt(52));
        System.out.println(Deck.get(CutPoint));
        System.out.println();
    }

    public static void CountdownEffect() throws InterruptedException{
        Thread.sleep(1000);
        for(int count=0; count<3; count++){
            System.out.print(".");
            Thread.sleep(1000);
        }
    }
} 

public class Player{

    public Player(ArrayList<Integer> h, int id, int n){
        Hand = new ArrayList<>(h);
        playerid = id;
        NoOfPlayers = n;
    }

    public ArrayList<Integer> Hand;
    public int playerid;
    public static int NoOfPlayers;

    public int SizeOfHand(){
        int s = Hand.size();
        return s;
    }

    public void DisplayHand() throws InterruptedException{
        System.out.print("Displaying ");
        if (playerid==1)
            System.out.print("player's");
        else if (playerid==2)
            System.out.print("computer player 1's");
        else if (playerid==3)
            System.out.print("computer player 2's");
        else if (playerid==4)
            System.out.print("computer player 3's");
        System.out.println(" hand:");
        Thread.sleep(1000);
        for(int count=0; count<7; count++){
            if (count<6)
                System.out.print(Hand.get(count) + ", ");
            else if (count==6)
                System.out.println(Hand.get(count) + ".");
        }
    }
}

public class PlayGinRummy {

    public PlayGinRummy(){}

    public static int NoOfPlayers;

    public static void DealDeck() throws InterruptedException{
        int cardno, playerno; // Tracks index of top card
        System.out.println("Please input the desired number of players (2-4): ");
        Scanner UserInput = new Scanner(System.in);
        NoOfPlayers = UserInput.nextInt(); 
        System.out.println();
        System.out.println();

        cardno=51;
        playerno=0;

        do{
            if (NoOfPlayers==2){
                Player hp = new Player(Player.Hand,1,NoOfPlayers); 
                Player cp1 = new Player(Player.Hand,2,NoOfPlayers);

                do{
                    if (playerno%2==0)
                        hp.Hand.add(DeckOfCards.Deck.get(cardno));
                    else if (playerno%2==1)
                        cp1.Hand.add(DeckOfCards.Deck.get(cardno));

                    DeckOfCards.Deck.remove(cardno);

                    playerno++;
                    cardno--;
                }while(hp.SizeOfHand()!=7 && cp1.SizeOfHand()!=7);

                hp.DisplayHand();
                cp1.DisplayHand();
            }
            else if (NoOfPlayers==3){
                Player hp = new Player(Player.Hand,1,NoOfPlayers);
                Player cp1 = new Player(Player.Hand,2,NoOfPlayers);
                Player cp2 = new Player(Player.Hand,3,NoOfPlayers);

                do{
                    if (playerno%3==0)
                        hp.Hand.add(DeckOfCards.Deck.get(cardno));
                    else if (playerno%3==1)
                        cp1.Hand.add(DeckOfCards.Deck.get(cardno));
                    else if (playerno%3==2)
                        cp2.Hand.add(DeckOfCards.Deck.get(cardno));

                    DeckOfCards.Deck.remove(cardno);

                    playerno++;
                    cardno--;
                }while(hp.SizeOfHand()!=7 && cp1.SizeOfHand()!=7 && cp2.SizeOfHand()!=7);

                hp.DisplayHand();
                cp1.DisplayHand();
                cp2.DisplayHand();
            }
            else if (NoOfPlayers==4){
                Player hp = new Player(Player.Hand,1,NoOfPlayers);
                Player cp1 = new Player(Player.Hand,2,NoOfPlayers);
                Player cp2 = new Player(Player.Hand,3,NoOfPlayers);
                Player cp3 = new Player(Player.Hand,4,NoOfPlayers);

                do{
                    if (playerno%4==0)
                        hp.Hand.add(DeckOfCards.Deck.get(cardno));
                    else if (playerno%4==1)
                        cp1.Hand.add(DeckOfCards.Deck.get(cardno));
                    else if (playerno%4==2)
                        cp2.Hand.add(DeckOfCards.Deck.get(cardno));
                    else if (playerno%4==3)
                        cp3.Hand.add(DeckOfCards.Deck.get(cardno));

                    DeckOfCards.Deck.remove(cardno);

                    playerno++;
                    cardno--;
                }while(hp.SizeOfHand()!=7 && cp1.SizeOfHand()!=7 && cp2.SizeOfHand()!=7 && cp3.SizeOfHand()!=7);

                hp.DisplayHand();
                cp1.DisplayHand();
                cp2.DisplayHand();
                cp3.DisplayHand();
            }
            else{
                System.out.println("The choice made is invalid, please try again.");
                System.out.println();
            }
        }while(NoOfPlayers!=2 && NoOfPlayers!=3 && NoOfPlayers!=4);       

        System.out.println();
    }
}    

由於“ main”方法必須是靜態的,因此它可以訪問的任何內容肯定也必須是靜態的,依此類推嗎?

不能。靜態方法可以訪問實例方法。 他們通過使用實例來做到這一點。 main創建實例以使用實例方法( main本身所在的類或其他類)是非常非常常見的。

因此,通常:

public static final void main(String[] args) {
    SomeClass instance = new SomeClass();
    instance.method();
}

如果您要制作的東西很小且完全是獨立的,則main創建它所在的類是很常見的。例如:

public class Simple {
    private String name;

    public static final void main(String[] args) {
        // Create a couple of instances
        Simple s1 = new Simple();
        Simple s2 = new Simple();

        // Use instance methods
        s1.setName("s1");
        s2.setName("s2");
        System.out.println(s1.getName());
        System.out.println(s2.getName());
    }

    private void setName(String name) {
        this.name = name;
    }

    private String getName() {
        return this.name;
    }
}

在那里,我使用了兩個單獨的實例進行強調。 我為它們使用了單個變量,但是當然,如​​果您要將它們視為分組列表或實例集,則可能會使用數組, ListSet 數組示例:

public class Simple {
    private String name;

    public static final void main(String[] args) {
        // Create the array (no instances are created)
        Simple[] simples = new Simple[2];

        // Create a couple of instances, set their names
        for (int n = 0; n < simples.length; ++n) {
            simples[n] = new Simple();
            simples[n].setName("s[" + n + "]");
        }

        // Use instance methods
        for (Simple s : simples) {
            System.out.println(s.getName());
        }
    }

    private void setName(String name) {
        this.name = name;
    }

    private String getName() {
        return this.name;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM