java - 如何跨不同类访问我的私有(private)变量?

标签 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 方法吗?我已经尝试这样做了,但遇到了很多麻烦。如果有人可以向我展示如何跨类访问变量,我将不胜感激!

最佳答案

这是一个稍微简化的示例,其中 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();
    }
}

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

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

关于java - 如何跨不同类访问我的私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27581347/

相关文章:

c - C 中的全局数据空间不足

c - 枚举C,全局变量错误: variable has initializer but incomplete type

java - 如何使用其他语言安装 Java?

java - setter 的 Lambda 表达式

php - 如何在 Laravel 中设置全局变量?

javascript - 在 lodash 中,为什么谓词和结果变量没有以 var 关键字作为前缀?

javascript - 如何以一种或另一种方式对从帖子返回的数据求和

java - 如果不需要@Override,如何强制Java编译器出错

java - 上下移动项目

java - DefaultHttpClient、证书、Https 和发布问题!