如何在不同的类中访问我的私有变量?

时间:2014-12-20 14:53:13

标签: java global-variables

我正致力于创造类似刽子手的游戏。它从四个字母单词的.txt文件中读取并随机选择其中一个单词,然后玩家将有7次尝试猜测单词...我还没有完成所有这些,我无法访问我的从一个类到另一个类的变量。这是我的代码:

package wordguessinggame2;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class WordGuessingGame2 {

    static class RandomWordProvider {

        public final List<String> words;

        public RandomWordProvider() {
        words = readFile();
    }

    public int randomInteger() {
        int randomInt = (int) (Math.random() * words.size());
        return randomInt;
    }

    private String getWord() {
        int randomPosition = randomInteger();
        String randomWord = words.get(randomPosition);
        return randomWord;
    }

    private List<String> readFile() {

        List<String> wordsList = new ArrayList<>();

        try {
            File fourLetterWords = new File(System.getProperty("user.home"),"Documents/FourLetterWords.txt");
            Scanner in = new Scanner(fourLetterWords);

        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (line!=null && !line.isEmpty()) {
                wordsList.add(line);
            }
        }
    } 
    catch (FileNotFoundException ex) {
        System.out.println("File not found.");
    }
    return wordsList ;
    }
}
    public static class PlayerCharacterEntry {

        private String playerEntry() {
            Scanner characterEntry = new Scanner(System.in);
            System.out.print("Enter a character: ");
            String playerInput = characterEntry.next();
            playerInput = playerInput.toUpperCase();
            return playerInput;
    }
}

    public static void main(String[] args) {

        Scanner wantToPlay = new Scanner(System.in);
        System.out.print("Welcome to the word guessing game! Would you like to play? ");
        String playerAnswer = wantToPlay.next();

        if (playerAnswer.equalsIgnoreCase("Yes")) {
            System.out.print("\nYour objective is to guess a four letter word by entering"
            + "\nletters on your keyboard. If you can not guess the word in seven attempts,"
            + "\nyou lose! You will be told if the letter you entered is in the word, and"
            + "\nyou will be told if the letter you entered is not in the word. You will be"
            + "\nallowed to guess the word any time during your seven attempts. If at anytime"
            + "\nyou would like to terminate the game, enter the word 'terminate'. Good Luck!"
            + "\n \n");
    }
        if (playerAnswer.equalsIgnoreCase("No")) {
            System.out.print("Maybe another time!");
            System.exit(0);
    }

RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();

randomWordProvider.getWord();
playerCharacterEntry.playerEntry();

if (randomWord.containsIgnoreCase(playerInput)){

    }

}
}

我在底部尝试从其他课程中访问randomWord和playerInput,但我不知道该怎么做。我仍然是编程新手,所以我不知道如何做所有事情。我会为每个变量做一个get和set方法吗?我已经尝试过这样做,而且我遇到了很多麻烦。如果有人可以告诉我如何跨类访问变量,那将非常感激!

2 个答案:

答案 0 :(得分:1)

以下是一个略微简化的示例,其中RandomWordProviderPlayerCharacterEntry类未嵌套在WordGuessingGame2中。 我只展示了我需要修改的方法:

class RandomWordProvider {   
    String getWord() {
        int randomPosition = randomInteger();
        String randomWord = words.get(randomPosition);
        return randomWord;
    }

    // ...
}

class PlayerCharacterEntry {
    String playerEntry() {
        Scanner characterEntry = new Scanner(System.in);
        System.out.print("Enter a character: ");
        String playerInput = characterEntry.next();
        playerInput = playerInput.toUpperCase();
        return playerInput;
    }
}

class WordGuessingGame2 {
    public static void main(String[] args) {

        // ...

        RandomWordProvider randomWordProvider = new RandomWordProvider();
        PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();

        randomWordProvider.getWord();
        playerCharacterEntry.playerEntry();
    }
}

请注意,我从privategetWord方法中删除了playerEntry修饰符, 否则无法从WordGuessingGame2访问它们。

从最严格的可能修饰符开始, 然后根据需要减少限制。

答案 1 :(得分:0)

不,私有变量只能从它自己的类中访问。强烈建议您创建公共getter和setter来维护封装的OO原则。

相关问题