简体   繁体   English

Getter 和 Setter 的问题 [Java]

[英]Trouble with Getters and Setters [Java]

I am fairly new to java (my first college course for it) and with everything being online, I'm having a hard time understanding things - so I apologize if this is stupid or obvious.我对Java相当陌生(我的第一门大学课程)并且所有内容都在线,我很难理解事物-因此,如果这是愚蠢的或显而易见的,我深表歉意。 In this project, I have two classes named "Basketball" and "BasketballDemo".在这个项目中,我有两个名为“Basketball”和“BasketballDemo”的类。 I am using a variety of methods to keep the score of a game between two basketball teams.我正在使用各种方法来保持两支篮球队之间的比赛比分。 The methods used are all in 'Basketball', while a 'while loop' lives in the other method (BasketballDemo) to keep running the methods when specified until the game ends.使用的方法都在“Basketball”中,而“while 循环”存在于另一个方法 (BasketballDemo) 中,以在指定时继续运行这些方法,直到游戏结束。 I am trying to use 'getters' and 'setters' to transfer the values between the two, but I am severely confused - no matter what I do, the values in 'BasketballDemo' are always 0 after running no matter how I slice it.我正在尝试使用 'getter' 和 'setter' 在两者之间传输值,但我很困惑 - 无论我做什么,无论我如何切片,'BasketballDemo' 中的值在运行后始终为 0。 I have done a profuse amount of research on how exactly it works, but my head is having a very hard time with what I'm sure for many is an easy subject.我已经对它的工作原理做了大量的研究,但我的头脑很难接受我确信对许多人来说是一个简单的主题。 I apologize in advance for the brevity of this code - because I don't know where the issue is I don't know exactly where in the code the problem is situated.我提前为这段代码的简洁道歉 - 因为我不知道问题出在哪里我不知道问题在代码中的确切位置。 Here are the two classes:下面是两个类:

Basketball.java:篮球.java:

import java.util.Scanner;

public class Basketball {
    private final String teamOne = "Lions";
    private final String teamTwo = "Bears";
    private int teamOneScore = 0;
    private int teamTwoScore = 0;
    private String gameState = "ongoing";

    public int scoreOnePoint(String whatTeam) {
        if (whatTeam.equalsIgnoreCase("Lions")) {
            Basketball newScore = new Basketball();
            newScore.setTeamOneScore(newScore.getTeamOneScore() + 1);
            System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
            return newScore.getTeamOneScore();
        }
        else if (whatTeam.equalsIgnoreCase("Bears")) {
            Basketball newScore = new Basketball();
            newScore.setTeamTwoScore(newScore.getTeamTwoScore() + 1);
            System.out.println("The Lions' score is now: " + newScore.getTeamTwoScore() + ".");
            return newScore.getTeamTwoScore();
        }
        else {
            System.out.println("ERROR: Entered invalid team name. Please try again.");
            return 0;
        }

    }

    public int scoreTwoPoints(String whatTeam) {
        if (whatTeam.equalsIgnoreCase("Lions")) {
            Basketball newScore = new Basketball();
            newScore.setTeamOneScore(newScore.getTeamOneScore() + 2);
            System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
            return newScore.getTeamOneScore();
        }
        else if (whatTeam.equalsIgnoreCase("Bears")) {
            Basketball newScore = new Basketball();
            newScore.setTeamTwoScore(newScore.getTeamTwoScore() + 2);
            System.out.println("The Lions' score is now: " + newScore.getTeamTwoScore() + ".");
            return newScore.getTeamTwoScore();
        }
        else {
            System.out.println("ERROR: Entered invalid team name. Please try again.");
            return 0;
        }

    }

    public int scoreThreePoints(String whatTeam) {
        if (whatTeam.equalsIgnoreCase("Lions")) {
            Basketball newScore = new Basketball();
            newScore.setTeamOneScore(newScore.getTeamOneScore() + 3);
            System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
            return newScore.getTeamOneScore();
        }
        else if (whatTeam.equalsIgnoreCase("Bears")) {
            Basketball newScore = new Basketball();
            newScore.setTeamTwoScore(newScore.getTeamTwoScore() + 3);
            System.out.println("The Bears' score is now: " + newScore.getTeamTwoScore() + ".");
            return newScore.getTeamTwoScore();
        }
        else {
            System.out.println("ERROR: Entered invalid team name. Please try again.");
            return 0;
        }

    }

    public void finished() {
        Scanner isFinished = new Scanner(System.in);
        System.out.println("Are you sure the game finished? (Y/N):");
        String finished = isFinished.nextLine();
        if (finished.equalsIgnoreCase("Y")) {
            Basketball isFinishedNow = new Basketball();
            isFinishedNow.setGameState(finished);
            if (isFinishedNow.getTeamOneScore() > isFinishedNow.getTeamTwoScore()) {
                System.out.println("The Lions win!");
            }
            else if (isFinishedNow.getTeamOneScore() < isFinishedNow.getTeamTwoScore()) {
                System.out.println("The Bears win!");
            }
            else {
                System.out.println("It's a tie!");
            }
            System.out.println("The game is finished!");
        }

        else {
            System.out.println("We aren't done here yet!");
        }
    }

    public int scoreCheck(String whatTeam) {
        if (whatTeam.equalsIgnoreCase("Lions")) {
            Basketball checkScore = new Basketball();
            System.out.println("The Lions are currently at " + checkScore.getTeamOneScore() + " points.");
            return checkScore.getTeamOneScore();
        }
        else if (whatTeam.equalsIgnoreCase("Bears")) {
            Basketball checkScore = new Basketball();
            System.out.println("The Bears are currently at " + checkScore.getTeamTwoScore() + " points.");
            return checkScore.getTeamTwoScore();
        }
        else {
            System.out.println("ERROR: You entered an invalid team name, please try again.");
            return 0;
        }
    }

    public void winningTeam() {
        Basketball whoIsWinning = new Basketball();
        if (whoIsWinning.getTeamOneScore() > whoIsWinning.getTeamTwoScore()) {
            System.out.println("The Lions are winning!");
        }
        else if (whoIsWinning.getTeamOneScore() < whoIsWinning.getTeamTwoScore()) {
            System.out.println("The Bears are winning!");
        }
        else {
            System.out.println("It's currently a tie!");
        }
    }

    public int getTeamOneScore() {
        return teamOneScore;
        }

    public void setTeamOneScore(int newScore) {
        this.teamOneScore = newScore;
    }

     public int getTeamTwoScore() {
        return teamTwoScore;
     }

    public void setTeamTwoScore(int newScore) {
        this.teamTwoScore = newScore;
    }

    public String getGameState() {
        return gameState;
    }

    public void setGameState(String newGameState) {
        this.gameState = newGameState;
    }

    public static void main(String[] args) {

    }

}

BasketBallDemo.java:篮球演示.java:

import java.util.Scanner;

public class BasketballDemo {

    public static void main(String[] args) {
        Basketball game = new Basketball();


        while (game.getGameState() == "ongoing") {
            Scanner getUpdateOne = new Scanner(System.in);
            System.out.println("Enter the team that scored, or 'finished' if the game is over: ");
            String gameUpdateOne = getUpdateOne.nextLine();

            Scanner getUpdateTwo = new Scanner(System.in);
            System.out.println("Enter the amount scored (1/2/3): ");
            int gameUpdateTwo = getUpdateTwo.nextInt();

            if (gameUpdateOne.equalsIgnoreCase("Finished")) {
                game.finished();
            }

            else if (gameUpdateOne.equalsIgnoreCase("Lions")) {
                if (gameUpdateTwo == 1) {
                    game.scoreOnePoint("Lions");
                    game.scoreCheck("Lions");
                    game.scoreCheck("Bears");
                    game.winningTeam();
                }
                else if (gameUpdateTwo == 2) {
                    game.scoreTwoPoints("Lions");
                    game.scoreCheck("Lions");
                    game.scoreCheck("Bears");
                    game.winningTeam();
                }
                else if (gameUpdateTwo == 3) {
                    game.scoreThreePoints("Lions");
                    game.scoreCheck("Lions");
                    game.scoreCheck("Bears");
                    game.winningTeam();
                }
            }
            else if (gameUpdateOne.equalsIgnoreCase("Bears")) {
                if (gameUpdateTwo == 1) {
                    game.scoreOnePoint("Bears");
                    game.scoreCheck("Lions");
                    game.scoreCheck("Bears");;
                    game.winningTeam();

                }
                else if (gameUpdateTwo == 2) {
                    game.scoreTwoPoints("Bears");
                    game.scoreCheck("Lions");
                    game.scoreCheck("Bears");
                    game.winningTeam();
                }
                else if (gameUpdateTwo == 3) {
                    game.scoreThreePoints("Bears");
                    game.scoreCheck("Lions");
                    game.scoreCheck("Bears");
                    game.winningTeam();

                }
            }
            else {
                System.out.println("ERROR: invalid entry, please try again.");
            }



        }



    }
}

TLDR; TLDR;

You have a couple issues, both of which are in Basketball .你有几个问题,都在Basketball You call winningTeam after every update in BasketballDemo .每次更新BasketballDemo后,您都会调用winningTeam Currently, this creates a new instance of Basketball , which means all your class variables are going to be 0, or whatever your initial value is.目前,这会创建一个Basketball的新实例,这意味着您的所有类变量都将为 0,或者您的初始值是什么。 You also create new instances of Basketball in your scoring methods.您还可以在您的得分方法中创建新的Basketball实例。 See below for details.详情请见下文。

Change:改变:

public void winningTeam() {
        //You are creating a new instance of Basketball.
        Basketball whoIsWinning = new Basketball();
        if (whoIsWinning.getTeamOneScore() > whoIsWinning.getTeamTwoScore()) {
            System.out.println("The Lions are winning!");
        }
        else if (whoIsWinning.getTeamOneScore() < whoIsWinning.getTeamTwoScore()) {
            System.out.println("The Bears are winning!");
        }
        else {
            System.out.println("It's currently a tie!");
        }
    }

It should be this:应该是这样的:

 public void winningTeam() {
        //You want to check the current instance of Basketball
        if (this.getTeamOneScore() > this.getTeamTwoScore()) {
            System.out.println("The Lions are winning!");
        }
        else if (this.getTeamOneScore() < this.getTeamTwoScore()) {
            System.out.println("The Bears are winning!");
        }
        else {
            System.out.println("It's currently a tie!");
        }
    }

Also, you are creating a new instance of Basketball when you score:此外,您在得分时正在创建一个新的Basketball实例:

 public int scoreOnePoint(String whatTeam) {
        if (whatTeam.equalsIgnoreCase("Lions")) {
            Basketball newScore = new Basketball();
            newScore.setTeamOneScore(newScore.getTeamOneScore() + 1);
            System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
            return newScore.getTeamOneScore();
        }
        else if (whatTeam.equalsIgnoreCase("Bears")) {
            Basketball newScore = new Basketball();
            newScore.setTeamTwoScore(newScore.getTeamTwoScore() + 1);
            System.out.println("The Lions' score is now: " + newScore.getTeamTwoScore() + ".");
            return newScore.getTeamTwoScore();
        }
        else {
            System.out.println("ERROR: Entered invalid team name. Please try again.");
            return 0;
        }

    }

You want something more like this:你想要更像这样的东西:

public int scoreOnePoint(String whatTeam) {
        if (whatTeam.equalsIgnoreCase("Lions")) {
          
            this.setTeamOneScore(this.getTeamOneScore() + 1);
            System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
            return this.getTeamOneScore();
        }
        else if (whatTeam.equalsIgnoreCase("Bears")) {
           
            this.setTeamTwoScore(this.getTeamTwoScore() + 1);
            System.out.println("The Lions' score is now: " + newScore.getTeamTwoScore() + ".");
            return this.getTeamTwoScore();
        }
        else {
            System.out.println("ERROR: Entered invalid team name. Please try again.");
            return 0;
        }

    }

Make sure you update all your scoring methods to do something similar to what is above.确保更新所有评分方法以执行与上述类似的操作。

Side note:边注:

You don't need Main in BasketBall .你不需要Main in BasketBall You can remove this in Basketball :您可以在Basketball删除它:

public static void main(String[] args) {

}

The problem is you are creating the new Basketball object in the methods of Basketball class.问题是您正在 Basketball 类的方法中创建新的 Basketball 对象。 You should be traversing the single game object which is crated in the main method of BasketballDemo.您应该遍历在 BasketballDemo 的 main 方法中创建的单个游戏对象。 Here is the example这是例子

Basketball.java篮球.java

public int scoreOnePoint(Basketball game, String whatTeam) {
      if (whatTeam.equalsIgnoreCase("Lions")) {
          game.setTeamOneScore(newScore.getTeamOneScore() + 1);
          System.out.println("The Lions' score is now: " + game.getTeamOneScore() + ".");
          return game.getTeamOneScore();
      }
      else if (whatTeam.equalsIgnoreCase("Bears")) {
          game.setTeamTwoScore(newScore.getTeamTwoScore() + 1);
          System.out.println("The Lions' score is now: " + game.getTeamTwoScore() + ".");
          return game.getTeamTwoScore();
      }
      else {
          System.out.println("ERROR: Entered invalid team name. Please try again.");
          return 0;
      }

}

Update other methods in similar way and in main method pass the same game object every time.以类似的方式更新其他方法,并且在 main 方法中每次都传递相同的游戏对象。

This is not the best design but you will get a clue.这不是最好的设计,但你会得到一个线索。

I took the liberty to address some code quality issues and significantly simplify the logic.我冒昧地解决了一些代码质量问题并显着简化了逻辑。 It felt like there were a few areas that the logic to error handle was repeated along with the setting of scoring.感觉有几个地方错误处理的逻辑随着评分的设置而重复。 The issues mentioned by the other answers have also been fixed most notably, handling of the objects and not recreating a new object every time we need to use it.其他答案提到的问题也得到了最显着的修复,即处理对象而不是每次需要使用它时都重新创建新对象。 I have attached the refactored code below.我在下面附上了重构的代码。 Do reach out with any doubts or clarifications.如有任何疑问或澄清,请与我们联系。

Basketball.java篮球.java

package stackoverflow;
import java.util.Scanner;

public class Basketball {
private final String teamOne;
private final String teamTwo;
private int teamOneScore = 0;
private int teamTwoScore = 0;
private String gameState = "ongoing";

public Basketball(String teamOne, String teamTwo) {
    this.teamOne = teamOne;
    this.teamTwo = teamTwo;
}
public void finished() {
    Scanner isFinished = new Scanner(System.in);
    System.out.println("Are you sure the game finished? (Y/N):");
    String finished = isFinished.nextLine();
    if (finished.equalsIgnoreCase("Y")) {
        setGameState(finished);
        if (getTeamOneScore() > getTeamTwoScore()) {
            System.out.println("The " + teamOne + " win!");
        }
        else if (getTeamOneScore() < getTeamTwoScore()) {
            System.out.println("The" + teamTwo + " win!");
        }
        else {
            System.out.println("It's a tie!");
        }
        System.out.println("The game is finished!");
    } else {
        System.out.println("We aren't done here yet!");
    }
}

public void winningTeam() {
    if (teamOneScore > teamTwoScore) {
        System.out.println("The " + teamOne + " are winning!");
    }
    else if (teamOneScore < teamTwoScore) {
        System.out.println("The " + teamTwo + " are winning!");
    }
    else {
        System.out.println("It's currently a tie!");
    }
}

public int getTeamOneScore() {
    return teamOneScore;
}

public void setTeamOneScore(int newScore) {
    System.out.println("The Bears score is now: " + newScore + ".");
    this.teamOneScore = newScore;
}

public int getTeamTwoScore() {
    return teamTwoScore;
}

public void setTeamTwoScore(int newScore) {
    System.out.println("The Lions score is now: " + newScore + ".");
    this.teamTwoScore = newScore;
}

public String getGameState() {
    return gameState;
}

public void setGameState(String newGameState) {
    this.gameState = newGameState;
}

}

BasketballDemo.java篮球演示.java

package stackoverflow;

import java.util.Scanner;

public class BasketballDemo {

private static final String BEARS = "bears";
private static final String LIONS = "lions";
private static final String FINISHED = "finished";

public static void main(String[] args) {
    Basketball game = new Basketball("Bears", "Lions");

    while (game.getGameState().equals("ongoing")) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the team that scored, or 'finished' if the game is over: ");
        String team = scanner.nextLine().toLowerCase();
        System.out.println("Enter the amount scored (1/2/3): ");
        int score = scanner.nextInt();

        switch(team) {
            case(FINISHED):
                game.finished();
                break;
            case(BEARS):
                game.setTeamOneScore(game.getTeamOneScore() + score);
                game.winningTeam();
                break;
            case(LIONS):
                game.setTeamTwoScore(game.getTeamTwoScore() + score);
                game.winningTeam();
                break;
            default:
                System.out.println("ERROR: invalid entry, please try again.");
                break;
        }
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM