Setters和Getters到不同的类

时间:2018-06-05 02:51:30

标签: java for-loop

我的问题是,我根本不知道用什么代码将我的getX方法的值从我的其他类主方法中获取。

package hangman;

公共班Hangman {

private int triesLimit;
private String word;

public void setTriesLimit(int triesLimit) {
    this.triesLimit = triesLimit;
}

public void setWord(String word) {
    this.word = word;
}

public int getTriesLimit() {
    return this.triesLimit;
}

public String getWord() {
    return this.word;
}


@Override
public String toString() {
    return ("Enter Secret Word " + this.getWord()
            + ".\nEnter max # of tries (Must be under 7) "
            + this.getTriesLimit());
}

}

这是从子类开始的,我试图将triesLimit的值存储到这个类main方法的主要部分中 包刽子手;

public class PlayHangman {

public static void main(String[] args) {
    Hangman hangman = new Hangman();
    Scanner scn = new Scanner(System.in);
    int triesCount = 0;
    int correctCount = 0;
    hangman.toString();
    int triesLimit = hangman.getTriesLimit();
    String secretWord = hangman.getWord();
    StringBuilder b = new StringBuilder(secretWord.length());
    for (int i = 0; i < secretWord.length(); i++) {
        b.append("*");
    }
    char[] secrectStrCharArr = secretWord.toCharArray();
    int charCnt = secretWord.length();
    for (int x = 0; triesCount < triesLimit; triesCount++) {
        while (charCnt >= 0) {
            System.out.println("Secrect Word :" + b.toString());
            System.out.println("Guess a letter :");

            char guessChar = scn.next().toCharArray()[0];
            for (int i = 0; i < secrectStrCharArr.length; i++) {
                if (guessChar == secrectStrCharArr[i]) {
                    b.setCharAt(i, guessChar);
                    correctCount++;
                } else if (guessChar != secrectStrCharArr[i]) {
                    triesCount++;
                    System.out.println("Incorrect: " + triesCount);hangmanImage(triesCount,correctCount);
                }
            }
        }
    }
}

我试着在这里查找,但无法找到在子/超类中使用的setter和getter

2 个答案:

答案 0 :(得分:1)

您需要在main方法中创建该类的实例,以访问该类中可用的变量和方法,如此

public class PlayHangman {

        public static void main(String[] args) {
       Hangman hangman = new Hangman();
       hangman.setTriesLimit(2)
        int value = hangman.getTriesLimit();

     }

您可以查看static关键字以直接访问该值,但这需要更多地了解OOP和JAVA。 这应该可以正常工作。

希望有所帮助:)

<强> EDITED

ToString方法只是将模型类中的所有内容转换为您已正确完成的String,但是您实现不正确....更改ToString内容所以

@Override
public String toString() {
    return ("The Secret Word you entered: " + this.getWord()
            + ".\n The max # of tries (Must be under 7): "
            + this.getTriesLimit());
}

您已初始化扫描程序,它可以执行您想要的操作,要求用户输入值,但是您还没有实现它,请将其添加到主方法中

    Scanner scn = new Scanner(System.in);
         hangman.setTriesLimit(scn.nextInt());
        hangman.setWord(scn.next());
       hangman.toString()//Will work now

现在试用和错误是你最好的朋友:) 和谷歌的一些问题,而不是等待答案:)

答案 1 :(得分:1)

Like rohit said, this is as simple as understand the basics of OOP, specific the encapsulation.

If you want to get a little deeper into OOP patterns, you could use the Observer pattern. This allows you to change the status of any class instance, even if they're not related by inheritance, aggregation, etc.

You can scale the solution by making List of Observer

Your observable interface

public interface IObservable {
  // Set the observer
  public void setObserver(IObserver iObserver);

  // Notify the observer the current status
  public void notifyObserver();
}

Your observer interface

public interface IObserver {
  public void update(boolean status);
}

Your observer implementation

public class PlayHangman implements IObserver {
  private boolean status = false;

  public void printStatus() {
      System.out.println("Status: " + (this.status ? "Win" : "Lose"));
  }

  @Override
  public void update(boolean status) {
      // The instance status is updated
      this.status = status;
      // Print the current status
      this.printStatus();
  }
}

Your observable implementation

public class Hangman implements IObservable{
  private String goalWord = "";
  private String currentWord = "";
  private int triesLimit = 0;
  private int tries = 0;
  private IObserver iObserver;

  public Hangman(String goalWord, int triesLimit) {
      this.goalWord = goalWord;
      this.triesLimit = triesLimit;
  }

  public void setCurrentWord(String currentWord) {
      this.currentWord = currentWord;
      this.notifyObserver();
  }

  public void addTry() {
      this.tries++;
      this.notifyObserver();
  }

  @Override
  public void setObserver(IObserver iObserver) {
      this.iObserver = iObserver;
  }

  @Override
  public void notifyObserver() {
    // True = win
    this.iObserver.update(this.tries < this.triesLimit && 
    this.goalWord.equals(this.currentWord));
  }
}

Your Main class

public class Main{
  public static void main(String[] args) {
    // PlayHangman (game status)
    PlayHangman playHangman = new PlayHangman();
    // Hangman initializes with a goalWord and the triesLimit
    Hangman hangman = new Hangman("HangmanJava", 5);
    // Set the observer
    hangman.setObserver(playHangman);
    // During the game you just can set the current word and add a try
    // You're not setting the status directly, that's the magic of the Observer pattern
    hangman.setCurrentWord("Hang");
    hangman.addTry();
    hangman.setCurrentWord("HangmanJava");
  }
}

Hope this helps and enjoy Java