Trouble with Getters and Setters [Java] - 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;
}
}
}
}

Related

Having to resubmit user choice over and over

Hey guys having some trouble with a multi part question. I'm trying to get a game of rock paper scissors done, when i try to test the code using the playRound method I have to input my choice over and over again and then it just prints out draw, you are the winner and the computer is the winner over and over, can anyone tell me where im going wrong ?
import java.util.Scanner;
import java.util.Random;
/**
* A class that will play a game of rock paper scissors.
*
* #author (your name)
* #version (a version number or a date)
*/
public class RockPaperScissors
{
private Scanner reader;
private int yourScore;
private int computerScore;
private Random ran = new Random();
public RockPaperScissors()
{
reader = new Scanner(System.in);
yourScore = 0;
computerScore=0;
Random ran = new Random();
}
public void printPrompt()
{
System.out.println("Enter your choice, paper, rock or scissors >");
String userChoice = userChoice();
System.out.println();
System.out.println();
System.out.println("Enter your choice, paper, rock or scissors >"+ userChoice);
}
public final String userChoice()
{
String userChoice= reader.next();
return userChoice;
}
public String computerChoice()
{
String compMove = ("");
int cpuChoice = ran.nextInt(3);
switch(cpuChoice)
{
case 0:
{
compMove = ("rock");
break;
}
case 1:
{
compMove = ("paper");
break;
}
case 2:
{
compMove = ("scissors");
break;
}
}
return (compMove);
}
public String findWinner(String yourChoice, String computerChoice)
{
yourChoice = userChoice();
computerChoice = computerChoice();
String Winner= null;
if (yourChoice.equals(computerChoice))
{
Winner = ("draw");
}
if (yourChoice.equals("rock"))
{
if (computerChoice.equals("paper"))
{
computerScore++;
Winner = ("computer");
}
else if (computerChoice == "scissors")
{
yourScore++;
Winner = ("you");
}
}
if (yourChoice.equals("paper"))
{
if (computerChoice.equals("scissors"))
{
computerScore++;
Winner = ("computer");
}
else if (computerChoice.equals("rock"))
{
yourScore++;
Winner = ("you");
}
}
if (yourChoice.equals("scissors"))
{
if (computerChoice.equals("rock"))
{
computerScore ++;
Winner = ("computer");
}
else if (computerChoice.equals("paper"))
{
yourScore++;
Winner = ("you");
}
}
if (!yourChoice.equals("rock||paper||scissors"))
{
computerScore++;
Winner = ("computer");
}
return Winner;
}
public void playRound()
{
printPrompt();
String computerChoice=computerChoice();
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
String findWinner = findWinner(computerChoice,userChoice);
{
if (findWinner.equals("draw"));
System.out.println("This game is a draw");
if (findWinner.equals("you"));
System.out.println("You are the winner");
if (findWinner.equals("computer"));
System.out.println("The computer is the winner");
}
System.out.println("You have " + yourScore + "and the computer has "+ computerScore);
}
}
The semicolon at the end of your if statements means that the if statement is COMPLETE. The lines immediately following your if statements are then stand-alone, they do not "belong" to the if statements...which is why they always run.
Change:
if (findWinner.equals("draw"));
System.out.println("This game is a draw");
To:
if (findWinner.equals("draw"))
System.out.println("This game is a draw");
Or even better:
if (findWinner.equals("draw")) {
System.out.println("This game is a draw");
}
Any advice on how i can get my initial choice to be saved so I don't
have to keep typing it in ?
In findWinner(), you're calling userChoice() and computerChoirce() AGAIN. At that point, the values are already in the parameters that were passed in, so you don't need those. Comment them out or remove them:
public String findWinner(String yourChoice, String computerChoice)
{
// You don't need these two lines:
//yourChoice = userChoice();
//computerChoice = computerChoice();
// ... other existing code ...
}
Then, in playRound(), you are calling both printPrompt() and userChoice(), which each have their own input mechanism:
printPrompt();
String computerChoice=computerChoice();
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
I'd get rid of printPrompt() and just do:
// printPrompt();
String computerChoice=computerChoice();
System.out.print("Enter your choice, paper, rock or scissors >");
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
You have some broken logic in findWinner(). This does not do what you think it does:
if (!yourChoice.equals("rock||paper||scissors"))
{
computerScore++;
Winner = ("computer");
}
I think what you were trying to do is make the computer win if the user did not type in "rock", "paper", or "scissors"? If so, change your if statements to else if statements and add a final else block:
public String findWinner(String yourChoice, String computerChoice)
{
String Winner = "";
if (yourChoice.equals(computerChoice))
{
Winner = "draw";
}
else if (yourChoice.equals("rock"))
{
if (computerChoice.equals("paper"))
{
computerScore++;
Winner = "computer";
}
else if (computerChoice.equals("scissors"))
{
yourScore++;
Winner = "you";
}
}
else if (yourChoice.equals("paper"))
{
if (computerChoice.equals("scissors"))
{
computerScore++;
Winner = "computer";
}
else if (computerChoice.equals("rock"))
{
yourScore++;
Winner = "you";
}
}
else if (yourChoice.equals("scissors"))
{
if (computerChoice.equals("rock"))
{
computerScore ++;
Winner = "computer";
}
else if (computerChoice.equals("paper"))
{
yourScore++;
Winner = "you";
}
}
else // user did not type "rock", "paper", or "scissors"!
{
computerScore++;
Winner = ("computer");
}
return Winner;
}
Lastly, MAJOR bug, you SWAPPED the order of your parameters when you called findWinner().
Change:
String findWinner = findWinner(computerChoice, userChoice);
To:
String findWinner = findWinner(userChoice, computerChoice);
Hope that helps!

How to repeat the question after the user chose the wrong answer on my quiz program in java

I want to make a quiz program in java, i need an output that if the user chose the wrong answer all question will repeat until the the user chose the correct answer and put an output that must display also the key to correction and i hope you all help guys on my quiz program in java. and i want to correct my score when 5 wrong answer will back in the question with two wrong answer. when i run the code the score is 178 points with the 5 wrong answer in code but when i perfect the quiz the score is 150 that's is the total score of my quiz
int score = 0;
int count = 0;
String name;
String age;
String subject;
String course;
String schoolyear;
name = JOptionPane.showInputDialog("Enter your name");
age = JOptionPane.showInputDialog("Enter your age");
subject = JOptionPane.showInputDialog("Enter your subject");
course = JOptionPane.showInputDialog("Enter your course");
schoolyear = JOptionPane.showInputDialog("Enter your school year today");
boolean a = true;
boolean b = true;
boolean c = true;
do {
if (a == true) {
String question1 =JOptionPane.showInputDialog("What year when the release of Java?\n"
+ ("2 points \n")
+ ("The answer is B\n")
+ "(A.)1990\n (B.)1991\n (C.)1998\n (D.)1980\n" );
if("B".equals(question1))
{
System.out.println("Correct\n");
score+= 2;
count++;
a = false;
}else{
System.out.println("Incorrect\n");
}
}
if (b == true) {
String question2 =JOptionPane.showInputDialog("Who created Java?\n"
+ ("2 points \n")
+ ("The answer is B\n")
+ "(A.)Manny Pacquio\n (B.)James Gosling\n (C.)James Bond\n (D.)Matt Damon\n");
if("B".equals(question2))
{
System.out.println("Correct\n");
score+= 2;
count++;
b = false;
}else{
System.out.println("Incorrect\n");
}
}
if (c == true) {
String question3 =JOptionPane.showInputDialog("In Which team where Java created?\n"
+ ("2 points \n")
+ ("The answer is D\n")
+ "(A.)Team Black\n (B.)Team White\n (C.)Team Brown\n (D.)Team Green\n" );
if("D".equals(question3))
{
System.out.println("Correct\n");
score+= 2;
count++;
c = false;
}else{
System.out.println("Incorrect\n");
}
} while (count <3);
}
Scanner input = new Scanner(System.in);
System.out.println("Your score: " + score);
System.out.println(100 *score/150 + "%");
if (score >=150) {
System.out.println("Excellent");
} else if (score >=140) {
System.out.println("Ultimatum!");
} else if (score >=120) {
System.out.println("Great Job!");
} else if (score >=100) {
System.out.println("Good Job!");
} else if (score >=80) {
System.out.println("Pass");
} else if (score >=60) {
System.out.println("Passangawa");
} else if (score >=40) {
System.out.println("Satisfy");
} else if (score >=20) {
System.out.println("Try again");
} else if (score >=0) {
System.out.println("Failed");
} else {
System.out.println("Wasted!");
```All question will repeat until the user chose the correct answer and i need the score will be correct when one or more wrong answer will back to answer again and the score will back to its correct score with the 28 question in total.
I suggest to use while loop and add some flag if the answer is correct and iterate until it will be correct
QUESTION
public class Question {
private String question;
private String answer;
public Question(String question, String answer) {
this.question = question;
this.answer = answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
MAIN
public static void main(String[] args) {
int score = 0;
Question q1 = new Question("What year when the release of Java?\n" + ("2 points \n")
+ "(A.)1990\n (B.)1991\n (C.)1998\n (D.)1980\n", "B");
Question q2 = new Question("What is hourse" + ("2 points \n") + "(A.)Animal\n (B.)Dog\n (C.)Human\n (D.)Lake\n",
"A");
List<Question> questionsList = new ArrayList<>();
questionsList.add(q1);
questionsList.add(q2);
for(Question question : questionsList) {
boolean isCorrectQuestion = false;
while (!isCorrectQuestion) {
String answer = JOptionPane.showInputDialog(question.getQuestion());
if (question.getAnswer().equals(answer)) {
System.out.println("Correct\n");
score += 2;
isCorrectQuestion = true;
} else {
System.out.println("Incorrect\n");
}
}
}
}
By the way first release of Java was in 1996
public static void main(String[] args) {
int score = 0;
int count = 0;
boolean a = true;
boolean b = true;
do {
if (a == true) {
String question1 = JOptionPane.showInputDialog("What year when the release of Java?\n"
+ ("2 points \n")
+ "(A.)1990\n (B.)1991\n (C.)1998\n (D.)1980\n");
if ("B".equals(question1)) {
System.out.println("Correct\n");
score += 2;
count++;
a = false;
} else {
System.out.println("Incorrect\n");
}
}
if (b == true) {
String question2 = JOptionPane.showInputDialog("#2: What year when the release of Java?\n"
+ ("2 points \n")
+ "(A.)1990\n (B.)1991\n (C.)1998\n (D.)1980\n");
if ("B".equals(question2)) {
System.out.println("Correct\n");
score += 2;
count++;
b = false;
} else {
System.out.println("Incorrect\n");
}
}
} while (count < 2);
}
}

Java dice game counter unable to add correctly

I wrote a dice game in java that rolls two dice and keeps score.
The entire game has a total of four classes but the problem I am facing is in my EyesHaveIt class.
It adds each turn to a total score but it is not calculating the math correctly.
I've tried to find what is causing it but with no success.
Can anyone help me find where the problem is?
public class EyesHaveIt {
Scanner kb = new Scanner(System.in);
private int turnScore;
private int computerTotalScore;
private int playerTotalScore;
private int computerTurnNumber;
private int playerTurnNumber;
public int roundPoints;
private String userName;
//Accepts a name value from PlayGame class.
public void init(String name) {
userName = name;
}
//This method starts the game with a computer turn.
public void playGame() {
computerTurn();
}
//Computers turn to roll the dice.
public void computerTurn() {
turnScore = 0;
System.out.println("Computer's turn: ");
while (turnScore < 20) {
rollTheDice();
computerTurnNumber++;
setComputerTotalScore(turnScore);
}
getGameScore();
enterToContinue();
}
//Checks users input(enter) to continue player turn.
public void enterToContinue() {
System.out.print("\nPress ENTER to continue ...");
try {
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
playerTurn();
}
//Players turn to roll the dice.
public void playerTurn() {
turnScore = 0;
System.out.println(userName + "'s turn:");
for (int i = 0; i < 5; i++) {
rollTheDice();
playerTurnNumber++;
getPlayerTotalScore(turnScore);
System.out.println("Roll again? (y/n) ");
char continueGame = kb.next().charAt(0);
continueGame = Character.toUpperCase(continueGame);
if (continueGame == 'Y') {
int test = 0;
} else {
getGameScore();
}
}
getGameScore();
computerTurn();
}
//Creates two dice from PairOfDice class and prints values rolled.
public void rollTheDice() {
PairOfDice dieOne = new PairOfDice();
PairOfDice dieTwo = new PairOfDice();
int die1 = dieOne.getDieOneValue();
int die2 = dieTwo.getDieOneValue();
System.out.println("\tRolled: " + die1 + " and " + die2);
whatWasRolled(die1, die2);
}
//Accepts int from rollTheDie and checks the value.
public void whatWasRolled(int die1, int die2) {
if (die1 == 1 && die2 == 1) {
System.out.println("\t Rolled snake eyes! All turn points will be doubled.");
roundPoints = (die1 + die2 * 2);
setScore(roundPoints);
} else if (die1 == 6 && die2 == 6) {
System.out.println("\t Rolled box cars! All points are gone now!");
roundPoints = 0;
setScore(roundPoints);
} else if (die1 == die2) {
System.out.println("\t Rolled double. . . lose all turn points.");
roundPoints = 0;
setScore(roundPoints);
} else {
roundPoints = die1 + die2;
setScore(roundPoints);
getTurnScore();
}
}
//Sets turnScore from whatWasRolled.
public void setScore(int roundPoints) {
turnScore = turnScore + roundPoints;
}
//Sets computer game score.
public void setComputerTotalScore(int turnScore) {
computerTotalScore = turnScore + computerTotalScore;
}
//Sets player game score.
public void setPlayerTotalScore(int turnScore) {
playerTotalScore = turnScore + playerTotalScore;
}
//computerTotalScore accesor returns an int.
public int getComputerTotalScore() {
return computerTotalScore;
}
//playerTotalScore accesor returns an int.
public int getPlayerTotalScore(int turnScore) {
playerTotalScore = turnScore + playerTotalScore;
return playerTotalScore;
}
//Returns turnScore after roll.
public int getTurnScore() {
System.out.println("\tCurrent score for this turn:" + turnScore);
return turnScore;
}
//How the game ends and current game score is displayed.
public void getGameScore() {
System.out.println(
"CURRENT GAME SCORE: Computer: " + computerTotalScore + "\t" + userName + ": " + playerTotalScore);
if (computerTotalScore >= 150) {
System.out.println("Sorry, " + userName + " you got beat by the computer!");
System.exit(0);
} else if (playerTotalScore > 150) {
System.out.println(userName + ", Congratulations! You beat the computer!");
System.exit(0);
}
}
}
how are you?
I have made 3 alterations in 2 classes.
have a look to see if it will work for you.
//Computers turn to roll the dice.
public void computerTurn() {
computerTurnNumber = 0; // here
turnScore = 0;
System.out.println("Computer's turn: ");
while (computerTurnNumber < 20) { // here is the amount of time the dice will be rolled
rollTheDice();
computerTurnNumber++;
setComputerTotalScore(turnScore);
}
getGameScore();
enterToContinue();
}
and
//Sets turnScore from whatWasRolled.
public void setScore(int roundPoints) {
turnScore = roundPoints; //here, before it was accumulating the points of each turn
}

How to pass information with a get properly in java

I new to java, still trying to get down arguments and passing info. I am writing a blood pressure program for school and have some issue passing info from one class to another.
I have a fully functioning system to take in the user info in one class and have to set up another to check if the average is above or below range. Now, the range is easy, but the passing of info is another thing.
So, here's the code i wrote. the ONLY thing I'm worried about is the very last part, the 'getSystolic' and its return. I need to send the info to another part of the program not in main or in this PressueInput (its BPChecker btw) and just banging my head against the problem.
Thank you for the input:
` import java.util.Scanner;
public class PressureInput
{
private int sysInput;
private int diaInput;
private int sysAvrg;
private int diaAvrg;
public PressureInput()
{
sysInput = 0;
diaInput = 0;
sysAvrg = 0;
diaAvrg = 0;
}
public void setSysPressure()
{
sysInput = 0;
while(sysInput <= 0 || sysInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
sysInput= cin.nextInt();
System.out.println("You have entered " + sysInput + "\n");
if(sysInput <=0 || sysInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
sysAvrg += sysInput;
}
public int getSysPressure()
{
return sysInput;
}
public void setDiaPressure()
{
diaInput = 0;
while(diaInput <= 0 || diaInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
diaInput= cin.nextInt();
System.out.println("You have entered " + diaInput + "\n");
if(diaInput <=0 || diaInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
diaAvrg += diaAvrg;
}
public int getDiaPressure()
{
return diaInput;
}
public void sysAvrgRead()
{
sysAvrg = sysAvrg / 3;
System.out.println("\n" + "The systolic averge is " + sysAvrg);
}
public void diaAvrgRead()
{
diaAvrg = diaAvrg / 3;
System.out.println("The diastolic averge is " + diaAvrg + "\n");
}
public void setSystolic(int sys)
{
sysAvrg = sys;
}
public int getSystolic()
{
return sys;
}
} `
If you have a funftion in the class, that exhibits the var, then it should be fine. You need to make PressureInput a object, with PressureInput varnamePI = new PressureInput();
Then, access the var through varnamePI.sysAvrg=0; or so...

Variable is not properly transferring over to method [duplicate]

This question already has answers here:
How do I get the variable of one method to be a variable in another method for Java?
(4 answers)
Closed 8 years ago.
I'm trying to take the output of another method and use it in another method. I know there are other questions that are similar to mine but the solutions that were in those questions never solved my problem, though they did help a little. Here's where I'm stuck (problem is at rewardBet() method):
class Player {
private ArrayList<Card>hand;
private double cash, bet;
//double cash, bet;
public Player(double theCash)
{
cash = theCash;
hand = new ArrayList<Card>();
bet = 0;
}
public double wagerBet()
{
Scanner in = new Scanner(System.in);
System.out.print("Wager a bet: ");
double bet = in.nextDouble();
cash = cash - bet;
System.out.println("You wagered " + bet + ". " + "Now you have " + cash + " cash left.");
return bet;
}
public void rewardBet()
{
bet = wagerBet(); //this is supposed to be taking whatever the user wagered as a bet in the previous method and
cash = cash + (bet * 2); // apply it to this formula in order to mutate the total cash the player has
System.out.println("You now have " + cash + "cash.");
}
Any suggestions as to how to get this bet variable input to carry over?
EDIT, here's the main method like you guys requested:
class BlackJack {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Deck myDeck = new Deck();
myDeck.shuffle();
Player me = new Player(1000);
Player dealer = new Player(0);
Card c = myDeck.dealCard();
me.wagerBet();
System.out.println("Your first card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your next card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your total hand is currently " + me.totalHand() + ".");
System.out.println("Dealer showing " + c);
dealer.hit(c);
c = myDeck.dealCard();
String answer;
System.out.print("Hit or Stay?");
answer = in.nextLine();
while(answer.equals("Hit") || answer.equals("hit"))
{
System.out.println("Your next card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your total hand is currently " + me.totalHand() + ".");
if(me.totalHand() == 21)
{
System.out.println("You win");
me.rewardBet();
System.exit(0);
}
else if(me.totalHand() < 21)
{
System.out.print("Hit or Stay?");
answer = in.nextLine();
}
else{
System.out.println("Player bust.");
System.exit(0);
}}
while(dealer.totalHand() < 17)
{
System.out.println("Dealer draws " + c);
dealer.hit(c);
c = myDeck.dealCard();
System.out.println("Dealer's total hand is currently " + dealer.totalHand() + ".");
if(dealer.totalHand() == 21)
{
System.out.println("Dealer wins.");
System.exit(0);
}
else if(dealer.totalHand() > 21)
{
System.out.println("Dealer bust. You win.");
me.rewardBet();
System.exit(0);
}
}
if(me.totalHand() > dealer.totalHand())
System.out.println("You win!");
me.rewardBet();
if(me.totalHand() < dealer.totalHand())
System.out.println("Loooooser");
if(me.totalHand() == dealer.totalHand())
System.out.println("Push. Nobody wins");
}
}
and to clarify my problem, the wagerBet() method asks for a double input from the user in the form of a bet. If the player wins his hand then the rewardBet() method will reward the player, giving him back the amount he bet plus the reward, hence 'bet * 2'. The problem is the rewardBet() method isn't recognizing the 'bet' input at all, I'm trying to figure out how to make it so. So for example I make a bet of 50, so now I have 950 dollars (1000 is default). I win the round so rewardBet() needs to give me 100 dollars. Right now it isn't giving me anything for winning.
Well, one problem is at the very last line of your main method:
if(me.totalHand() > dealer.totalHand())
System.out.println("You win!");
me.rewardBet();
You need to wrap this body in braces - the if statement if only functioning on the print statement. Although this doesn't seem as though it will fix the problem that you've described.
Perhaps you should consider doing a different design altogether, and avoid using so much duplicate code.
BlackJack:
public class BlackJack
{
private Deck deck;
private Player me;
private Player dealer;
public static void main(String[] args)
{
BlackJack game = new BlackJack();
game.run();
}
public BlackJack()
{
deck = new Deck();
deck.shuffle();
me = new Player("Joe", 1000.0);
dealer = new Player("Dealer", 0);
}
public void run()
{
double bet = requestBet(me);
// Deal your first two cards
dealNextCard(me, "Your first card is ");
dealNextCard(me, "Your second card is ");
me.printHandTotal();
// Deal dealer's first card
dealNextCard(dealer, "Dealer showing ");
while(requestHitOrStay())
{
dealNextCard(me, "Your next card is ");
me.printHandTotal();
if(me.totalHand() == 21)
{
System.out.println(me.getName() + " wins!");
rewardBet(me, bet);
System.exit(0);
}
else if(me.totalHand() > 21)
{
System.out.println(me.getName() + " bust!");
System.exit(0);
}
}
while(dealer.totalHand() < 17)
{
dealNextCard(dealer, "Dealer draws ");
dealer.printHandTotal();
if(dealer.totalHand() == 21)
{
System.out.println(dealer.getName() + " wins!");
System.exit(0);
}
else if(dealer.totalHand() > 21)
{
System.out.println(dealer.getName() + " bust. You win!");
rewardBet(me, bet);
System.exit(0);
}
}
if(me.totalHand() > dealer.totalHand())
{
System.out.println("You win!");
rewardBet(me, bet);
}
else if(me.totalHand() < dealer.totalHand())
{
System.out.println("Loooooser");
}
else
{
System.out.println("Push. Nobody wins");
}
}
public boolean requestHitOrStay()
{
System.out.print("Hit or Stay? ");
Scanner in = new Scanner(System.in);
return in.nextLine().toLowerCase().equals("hit");
}
public void dealNextCard(Player p, String prefix)
{
Card c = deck.dealCard();
System.out.println(prefix + c);
p.addCard(c);
}
public double requestBet(Player p)
{
Scanner in = new Scanner(System.in);
double bet = Integer.MAX_VALUE;
while(bet > p.getCash())
{
System.out.print("Wager a bet: ");
bet = in.nextDouble();
}
p.setCash(p.getCash() - bet);
System.out.println(p.getName() + " wagered " + bet + ". " + "Now they have " + p.getCash() + " cash left.");
return bet;
}
public void rewardBet(Player p, double bet)
{
p.setCash(p.getCash() + bet * 2);
System.out.println(p.getName() + " now has " + p.getCash() + " cash.");
}
}
Player:
public class Player
{
private ArrayList<Card> hand;
private double cash;
private String name;
public Player(String playerName, double startingCash)
{
hand = new ArrayList<Card>();
cash = startingCash;
name = playerName;
}
public void addCard(Card c)
{
hand.add(c);
}
public int totalHand()
{
int total = 0;
for(Card c : hand)
{
total += c.getValue();
}
return total;
}
public void printHandTotal()
{
System.out.println(name + "'s' total hand is currently " + totalHand() + ".");
}
public String getName()
{
return name;
}
public double getCash()
{
return cash;
}
public void setCash(double cash)
{
this.cash = cash;
}
}

Categories