简体   繁体   中英

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. In this project, I have two classes named "Basketball" and "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. 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. 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:

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:

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;

You have a couple issues, both of which are in Basketball . You call winningTeam after every update in BasketballDemo . 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. You also create new instances of Basketball in your scoring methods. 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:

 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 . You can remove this in Basketball :

public static void main(String[] args) {

}

The problem is you are creating the new Basketball object in the methods of Basketball class. You should be traversing the single game object which is crated in the main method of BasketballDemo. Here is the example

Basketball.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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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