2014-12-20 2 views
0

저는 행맨 같은 게임을 만드는 중입니다. 그것은 .txt에서 네 글자 단어의 파일을 읽고 무작위로 단어 중 하나를 선택하면 플레이어는 단어를 추측하는 7 가지 시도를 할 것입니다. 아직 완료하지는 않았지만 한 클래스에서 내 변수에 액세스하는 데 문제가 있습니다. 다른쪽에. 여기 내 코드입니다 : 내 다른 클래스에서 randomWord 및 playerInput에 액세스하려고 바닥에 여기다른 클래스에서 개인 변수에 어떻게 액세스합니까?

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)){ 

    } 

} 
} 

하지만 난 그렇게하는 방법을 모르겠어요. 나는 아직도 프로그래밍에 익숙하지 않으므로 아직 모든 것을 수행하는 방법을 모른다. 각 변수에 대해 get 및 set 메서드를 사용합니까? 나는 그 일을 시도했지만 그 일로 많은 어려움을 겪고 있습니다. 누군가가 수업을 통해 변수에 액세스하는 방법을 보여줄 수 있다면 크게 감사하겠습니다!

+0

접근 자 생성시 문제점이 무엇입니까? – rafalopez79

+0

@ rafalopez79 잘 때 개인 문자열 playerInput; 그런 다음 메소드를 가져오고 설정하십시오. 내 인스턴스가 내 주요 메서드에서 작동하지 않습니다. – NEPat10

+0

전용 멤버는 정의 자체로 클래스 자체에서만 액세스 할 수 있습니다. 내가 다른 클래스 사용하여 액세스하려는 rafalopez79 같은 get/set 말했다 – Totem

답변

1

여기에 RandomWordProviderPlayerCharacterEntry 클래스가 WordGuessingGame2 안에 중첩되지 않은 약간 간단한 예가 있습니다. 내가 수정하는 데 필요한 메소드만을 보여 나는 getWordplayerEntry 방법에서 private 수정을 떨어

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(); 
    } 
} 

공지 사항, 그렇지 않으면 그들은 WordGuessingGame2에서 액세스 할 수 없습니다.

최대한 엄격한 수정 자로 시작하여 으로 시작한 다음 필요에 따라 제한을 줄이는 것이 좋습니다.

0

아니요, 개인 변수는 자체 클래스에서만 액세스 할 수 있습니다. 캡슐화의 OO 원칙을 유지하려면 공개 getter 및 setter를 만드는 것이 좋습니다.

+0

당신이 이것을 이해하지 않았다 감사합니다. – NEPat10

관련 문제