Trouble making Java Roulette game - java

I'm working on a roulette game and I'm having an error with my makeDecision method in my Roulette class. The reason is because I am having trouble with the updatePot method in my Player class and am not sure what to do in it. I am using 4 classes, here is my code for each:
public class Assign3 {
public static void main(String[] args) {
Roulette roulette = new Roulette();
roulette.run();
}
}
and
public class Roulette {
private String decision;
Player player = new Player();
Wheel wheel = new Wheel();
private void makeDecision(){
String bet = player.getBet();
try {
int value = Integer.parseInt(bet);
if (value == wheel.getValue()){
decision = " you win 40 times your bet";
player.updatePot(40);
} else {
decision = "you lose the game";
player.updatePot(0);
}
} catch (NumberFormatException e){
if (bet.equals("odd")){
if (wheel.getValue() %2 == 0){
decision = "you lose the game";
player.updatePot(0);
} else {
decision = "you win double your bet";
player.updatePot(2);
}
} else if (bet.equals("equals")){
if (wheel.getValue() %2 == 0){
decision = "you win double your bet";
player.updatePot(2);
}
}
}
}
private void displayDecision(){
}
public void run(){
System.out.println("Welcome to Cache Creek style Roulette..bet an amount and type\n"
+ " if you select the correct colour, you win double your bet\n"
+ " if you select the correct odd/even, you win double your bet\n"
+ " if you select the right number, you win 40 times your bet\n"
+ " otherwise you lose your bet\n"
+ " If you lose all your money, the game is over");
do {
player.setBetAmount();
player.setBet();
wheel.spin();
wheel.display();
makeDecision();
displayDecision();
} while (true);
}
}
and
package Assignment3;
import java.util.Scanner;
public class Player {
private int pot = 0;
private int amount = 0;
Scanner input = new Scanner(System.in);
public void setBetAmount() {
System.out.print("\nHow much do you want to bet? ");
amount = input.nextInt();
int pot =100;
if (amount > pot || amount < 1){
System.out.print("Invalid bet amount..How much do you want to bet? ");
amount = input.nextInt();
}
}
public void setBet() {
System.out.print("What is your bet? (odd/even/red/black/exact number)");
}
public String getBet() {
return null;
}
public void updatePot(int i) {
}
}
and
package Assignment3;
import java.util.Random;
public class Wheel {
private int value;
private String colour;
Random random;
public Wheel(){
value = 0;
colour = null;
random = new Random();
}
public int getValue(){
return value;
}
public void setValue(int value){
this.value = value;
}
public String getColour(){
return colour;
}
public void spin(){
value = random.nextInt(39)+1;
colour = (random.nextInt(1)==0)?"red":"black";
}
public void display(){
System.out.print(value+" "+colour);
}
}

the input for your program has to be a String because your Player can input both text or a specific number. You then have to check this String for the occurence of either (odd/even/red/black) or a valid number. If neither is true then the input is invalid.
When looking at your code you need to think about how you want your updatePot method to work.
Should it set the pot to the given value (that's what the method name would suggest to me)
Should it add the given value to the pot or
Should it multiply the current pot value by the given value
When you have decided how it should work you have to update your Roulette.makeDecision() method.
Good luck with your assignment!
Markus

Just change the datatype of bet from String to int and then add your updatePot methode. You will also need to adjust your NumberFormatException.

Related

Vector in java always overwriting everything with the last value

I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.

Can't calculate of the total sales of the day form my code, everytime it shows zero(0)

So, I wrote this code and its working fine but when i try to check total sale it shows zero(0).
in this part-
public void totalSales(){
getTotal();
System.out.println("Total sales is "+getTotal());
}.
I am struggling to save the previous values to get the total sales. And also how do I take multiple input from the menu? Any kind of help would be appreciated. If you see an area of improvement, do let me know. Thank You!
import `java.util.InputMismatchException`;
import java.util.Scanner;
import `java.util.ArrayList`;
public class Main {
static double a;
ArrayList<Product> cart = new ArrayList<Product> ();
Scanner scanner = new Scanner(System.in);
double vat = 0.5;
boolean done = false;
public Main() {
cart.add(new Product("Vegetable", 8.00));
cart.add(new Product("Deodrant", 56.00));
cart.add(new Product("Beverages", 35.00));
cart.add(new Product("Home Essentials", 10.00));
cart.add(new Product("Bakery", 20.50));
cart.add(new Product("Snacks", 15.00));
}
public void displayCart() {
for (int i = 0; i < cart.size(); i++) {
switch (cart.get(i).quantitySelected){
case 0:
System.out.println(i + ": " + cart.get(i).name + " Not Selected.");
break;
default:
System.out.println(i + ": " + cart.get(i).name + " Selected: " + cart.get(i).quantitySelected);
break;
}
}
}
public void addToCart(int product, int amount) {
cart.get(product).select(amount);
}
public void getSelection() {
int productSelected;
System.out.println("Enter the Product Value: \nOr \nEnter Done to End and See The Total. ");
try {
productSelected = scanner.nextInt();
} catch (InputMismatchException e) {
done = true;
return;
}
System.out.println("Enter Amount To Select: ");
int amount = scanner.nextInt();
cart.get(productSelected).select(amount);
}
public double getSubtotal() {
double cost = 0.00;
for (Product product : cart) {
cost += product.cost * product.quantitySelected;
}
return cost;
}
public double getTotal() {
return (getSubtotal() + getSubtotal()*vat);
}
public void totalSales(){
getTotal();
System.out.println("Total sales is "+getTotal());
}
public void finnishPurchase() {
System.out.println("---------------------");
System.out.println("Subtotal: " + getSubtotal());
System.out.println("Vat: " + vat);
System.out.println("Total: " + getTotal());
}
public static void main(String[] args) {
Main store = new Main();
while (!store.done) {
store.displayCart();
store.getSelection();
}
store.finnishPurchase();
System.out.println("Enter the password");
Scanner input=new Scanner(System.in);
String pw=input.next();
String actual="abc123";
boolean check=pw.equals(actual);
if(check==true)
{
System.out.println("Correct password.Here is the access");
Main c=new Main();
c.totalSales();
}
else
{
System.out.println("Incorrect password.Try again");
}
}
}
public class Product {
String name;
double cost;
int quantitySelected = 0;
public Product(String name, double cost) {
this.name = name;
this.cost = cost;
}
public void select(int quantity) {
quantitySelected = quantity;
}
}
I fixed your total issue.
You start a new main for no reason which resets the total to 0.
The fix was just to use the old main(Check the environment i tested in) to get the total.
I don't understand what you mean by getting mutiple inputs from the menu, however, it loops fine to select products one by one. I adapted the code to limit the number of products. All I did was add a limit variable to each object(you can use static to add a global limit). If you wanted to retrieve all users' totals you would have to store them then retrieve them and add them up.
The code I made.
Edit:
In order to take multiple item you just have to loop your nextInt() statements.
Code(Main.java):
System.out.println("Enter the Products and amounts(eg. 1(product) 20(amount)) Value: \nOr \nEnter Done to End and See The Total. ");
while(true){
try {
productSelected = scanner.nextInt();
int amount = scanner.nextInt();
if((amount+cart.get(productSelected).quantitySelected) <= cart.get(productSelected).limit)
cart.get(productSelected).select(amount);
else
System.out.println("Limit reached for item:"+cart.get(productSelected).name);
} catch (InputMismatchException e) {
done = true;
return;
}
}
The menu won't redisplay the user menu and will wait for the user to put done(or the wrong input). The user is able to put products line by line or all in one line(eg. 1 10 2 5 done) and get their total(check the code I tested on).

how to pass parameters to an array in another class?

This is my first time posting on StackOverflow, but I have visited many times. I am taking a computer science class and I ran into a problem that I have not been able to resolve through research. The assignment is to create a NBATeam class with instance variables and constructors and a NBA client that receives parameters of the names of players from the user and passes them to an array in the first class.
So the problem that I ran into is when I run my program, and I enter player names and pass them to the array, the first array of names are deleted. The names entered into the most recent array are fine, however.
I apologize if my terminology is wrong I am still a newb!
Thank you so much for any help you can give me.
I will insert my code below. My problem is where it says [null]. Also I entered bob for the first team and brian for the second team but bob is in the second team's array.
Please help!
Create NBA team of Heats
Add a player to team Heats? (yes/no)
yes
Enter the name of the player:
bob
Add one more player to Heats?
no
Create NBA team of Spurs
Add a player to team Spurs? (yes/no)
yes
Enter the name of the player:
brian
Add another player to Spurs?
no
***Heat Wins!***
Heats[null]Wins: 4 Loses: 0
Spurs[bob]Wins: 0 Loses: 4
import java.util.*;
public class NBA {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String ifAddPlayer, playerName = null;
//construct Team Heat
System.out.println("Create NBA team of Heats");
NBATeam heats = new NBATeam("Heats");
System.out.println("Add a player to team Heats? (yes/no)");
ifAddPlayer = input.next();
while(ifAddPlayer.equalsIgnoreCase("yes")) {
System.out.println("Enter the name of the player: ");
heats.addPlayer(playerName);
playerName = input.next();
System.out.println("Add one more player to Heats?");
ifAddPlayer = input.next();
}
//construct team Spurs.
System.out.println("Create NBA team of Spurs");
NBATeam spurs = new NBATeam("Spurs");
System.out.println("Add a player to team Spurs? (yes/no)");
ifAddPlayer = input.next();
while(ifAddPlayer.equalsIgnoreCase("yes")) {
System.out.println("Enter the name of the player: ");
spurs.addPlayer(playerName);
playerName = input.next();
System.out.println("Add another player to Spurs?");
ifAddPlayer = input.next();
}
playAGame(heats,spurs);
System.out.println(heats.toString());
System.out.println(spurs.toString());
}
public static void playAGame(NBATeam heats, NBATeam spurs) {
for(int game = 0; game < 7; game++){
double score = Math.random();
if (score < .5) {
heats.winAgame(spurs);
}
else{
spurs.winAgame(heats);
}
if(spurs.nWin()==4 || heats.nWin()==4) {
break;
}
}
if(spurs.nWin()>heats.nWin()) {
System.out.println("***Spurs Win!***");
}
else
System.out.println("***Heat Wins!***");
}
}
import java.util.Arrays;
public class NBATeam {
private String sTeamName;
private int nWin;
private int nLoss;
private int nPlayer;
private String [] playerArray = new String[nPlayer];
public NBATeam(String sTeamName) {
this.sTeamName = sTeamName;
nPlayer=0;
}
public int nWin() {
return nWin;
}
public int nLoss() {
return nLoss;
}
public String getTeamName(){
//gets team's Name
return sTeamName;
}
public String toString() {
return sTeamName + Arrays.toString(playerArray)+ "Wins: " + nWin +
" Loses: " + nLoss;
}
public void lossAgame() {
this.nLoss++;
}
public void winAgame(NBATeam team2) { //To win over the team
nWin++;
team2.setLoss(team2.nLoss()+1);
//teamB.lossAgame();
}
public int getLossNumber() {
return this.nLoss;
}
public void setLoss(int l) {
this.nLoss=l;
}
public int getWinNumber() {
return this.nWin;
}
public void setWin(int w) {
this.nWin=w;
}
public void addPlayer(String player) {
String temp[] = playerArray;
playerArray = Arrays.copyOf(temp, temp.length+1);
playerArray[nPlayer] = player;
nPlayer++;
}
public String[] getPlayerArray() {
return playerArray;
}
public void setPlayerArray(String[] playerArray) {
this.playerArray = playerArray;
}
}
You start with an initial value of null in playerName, and then you add the playerName before getting the value. This,
heats.addPlayer(playerName);
playerName = input.next();
is reversed. It should be
playerName = input.next();
heats.addPlayer(playerName);
And, you were consistent. This,
spurs.addPlayer(playerName);
playerName = input.next();
is likewise reversed. And should be
playerName = input.next();
spurs.addPlayer(playerName);
I would suggest you limit the visibility of your variables. If you had
String playerName = input.next();
heats.addPlayer(playerName);
it would limit the possibility of adding the player before you set it.

What is the best method to get the index of a String or Char Array?

I would like to know what is the best way to get the index of a specific letter in a word. The reason i am doing this, is because i am making and modifying a Hangman game. I am already done with the game and it works good, however i want to implement a score based system. I created a method called keepScore() that takes a boolean value to see if the answer is right or wrong. If it is right, i am going to add 10 points for each letter found. If its wrong, i will deduct 10 points. My method keepScore() is implemented incorrectly any help?
Hangman.java
import Game.Game;
import Prompter.Prompter;
/* This class is the main class that starts the game.
* It instantiates the Game and Prompter objects.
*/
public class Hangman {
public static void main(String[] args) {
//Check if an argument has been passed, we expect the answer to be passed
if(args.length == 0) {
System.out.println("Expected: Java Hangman <answer>");
System.err.println("Answer is required!");
System.exit(1);
}
System.out.println("Welcome to Hangman!");
//Create an instance of our game
Game game = new Game(args[0]);
//Create an instance of our prompter
Prompter prompter = new Prompter(game);
//Starts the game
while (game.getRemainingTries() > 0 && !game.isWon()) {
prompter.displayProgress();
prompter.promptForGuess();
}
//Displays the outcome of the game
prompter.displayOutcome();
}
}
Game.java
package Game;
/* This class is responsible for implementing the game
* logic.
*/
public class Game {
//Declare our member variables
public final static int TOTAL_TRIES = 3;
public final static int MAX_SCORE_POINTS = 10;
private String mAnswer;
private String lettersHit;
private String lettersMissed;
private int score;
//Default constructor
public Game(String answer) {
//Initialize our member variables
mAnswer = answer.toLowerCase();
lettersHit = "";
lettersMissed = "";
}
//This method checks to see if the letter was a hit or a miss
public boolean checkLetter(char letter){
letter = validateGuess(letter);
boolean isHit = mAnswer.indexOf(letter) != -1;
//If correct
if (isHit) {
//Add the letter to the lettersHit pool
lettersHit += letter;
keepScore(isHit);
System.out.println("Hit! Score: " + score);
}else {
//Add the letter to the lettersMissed pool
lettersMissed += letter;
keepScore(isHit);
System.out.println("Missed! Score: " + score);
}
return isHit;
}
private void keepScore(boolean isHit) {
if(isHit) {
for (int i = 0; i < lettersHit.length(); i++) {
score += MAX_SCORE_POINTS;
}
} else {
for (int i = 0; i < lettersMissed.length(); i++ ) {
score -= MAX_SCORE_POINTS;
}
}
}
/*
This method handles an empty string input. For example,
if the user were to press enter on input a 0 length String
will cause the program to crash.
*/
public boolean checkLetter(String letters) {
if (letters.length() == 0) {
throw new IllegalArgumentException("No letter entered");
}
return checkLetter(letters.charAt(0));
}
//This method validates the user guess
private char validateGuess(char letter) {
//If the character is not a letter
if (!Character.isLetter(letter)) {
//Ask user for a valid letter
throw new IllegalArgumentException("A letter is required!");
}
//If entry was valid, convert character to lowercase
letter = Character.toLowerCase(letter);
//Check if the letter has been guessed already
if (lettersHit.indexOf(letter) != -1 || lettersMissed.indexOf(letter) != -1) {
throw new IllegalArgumentException("The letter " + letter + " has already been guessed");
}
return letter;
}
//This method keeps track of the user's game progress
public String getCurrentProgress() {
String progress = "";
//For each character in the array of strings of mAnswer
for (char letter : mAnswer.toCharArray()) {
char display = '-';
if (lettersHit.indexOf(letter) != -1){
display = letter;
}
progress += display;
}
return progress;
}
//Get the current remaining tries
public int getRemainingTries() {
return TOTAL_TRIES - lettersMissed.length();
}
//Get the current answer
public String getAnswer() {
return mAnswer;
}
//This method checks if the game is won.
public boolean isWon() {
return getCurrentProgress().indexOf('-') == -1;
}
public int getScore(){
return score;
}
}
Prompter.java
package Prompter;
import Game.Game;
import java.util.Scanner;
/* This class is responsible for displaying instructions and information to the user
* regarding the game.
*/
public class Prompter {
//The game object
private Game mGame;
private boolean isHit;
private boolean acceptable;
//Default constructor
public Prompter(Game game) {
//Get the instance of our game
mGame = game;
isHit = false;
acceptable = false;
}
//This method prompts the user for a guess
public boolean promptForGuess() {
//Create an instance of scanner
Scanner scanner = new Scanner(System.in);
//Loop for input
do {
System.out.println("Please enter a letter: ");
String guess = scanner.nextLine();
try {
isHit = mGame.checkLetter(guess);
acceptable = true;
}catch (IllegalArgumentException iae) {
System.out.printf("%s. Please try again!%n", iae.getMessage());
}
} while (!acceptable);
return isHit;
}
//This method displays the progress
public void displayProgress() {
System.out.printf("You have %d tries to guess the answer" +
" before you are taken to the gallows. Try to solve: %s%n", mGame.getRemainingTries(),
mGame.getCurrentProgress());
}
//This method displays the outcome of the game
public void displayOutcome() {
if( mGame.isWon()) {
System.out.printf("Congratulations! you won with %d tries remaining.%n" +
"Your total score: %d%n", mGame.getRemainingTries(), mGame.getScore());
}else {
System.out.printf("Bummer! The answer was: %s", mGame.getAnswer());
}
}
}
Look at this method of yours:
private void keepScore(boolean isHit) {
if(isHit) {
for (int i = 0; i < lettersHit.length(); i++) {
score += MAX_SCORE_POINTS;
}
} else {
for (int i = 0; i < lettersMissed.length(); i++ ) {
score -= MAX_SCORE_POINTS;
}
}
}
It doesn't add MAX_SCORE_POINTS times the number of good letters you just found, it does so with the number of good letters in lettersHit. Now, what is in lettersHit ? Well, there is all the letters you found since the start.
So you'll have :
word to guess: anaconda
letter: a
lettersHit = "a", score += (lettersHit.length * 10) = 10
letter: c
lettersHit = "ac", score += (lettersHit.length * 10) = 30
You could just use StringUtils.countMatches(mAnswer, letter); to get the number of occurence, hence the score.

Calculating wins/losses, winning percentage and total winnings

I'm just practicing Java and pretty new to this. I was just trying to create a Random Number Generator program which tracks a player's wins, losses, winning percentage and total winnings. The logic of the program is that a player gets 3 chances per session and the computer generates a random number which the player needs to guess or rather should match.
I have three classes currently: Game(which holds the main logic), Player(which should have the wins/losses etc.. is what I'm guessing) and RandomNumberGenerator(which generates random numbers).
I've got a start with the program but confused whether I need to declare gamesWon, gamesLost, totalWinnings, winPercent as separate variables in the player class? Any help would be appreciated.
Here's the player class so far:
public class Player {
private String name;
private int totalWinnings;
private int gamesWon;
private int gamesLost;
public Player() {
this.name = "default";
this.totalWinnings = 0;
this.gamesWon = 0;
this.gamesLost = 0;
}
public Player(String name) {
this.name = "default";
this.totalWinnings = 0;
this.gamesWon = 0;
this.gamesLost = 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGamesWon() {
return gamesWon;
}
public void setGamesWon(int gamesWon) {
this.gamesWon += gamesWon;
}
public int getGamesLost() {
return gamesLost;
}
public void setGamesLost(int gamesLost) {
this.gamesLost += gamesLost;
}
public void setTotalWinnings(int totalWinnings) {
this.totalWinnings += totalWinnings;
}
public int getTotalWinnings() {
return totalWinnings;
}
}
Game Class:
public class Game {
private Player player;
private LuckyNumberGenerator lng;
public Game() {
player = new Player();
lng = new LuckyNumberGenerator();
}
private void eventLoop() {
Scanner scanner = new Scanner(System.in);
int choice = 0;
boolean exit = false;
while (!exit) {
System.out.println("Welcome to the Guessing Game");
System.out.println("==============================");
System.out.println("(1) Set Up New Player");
System.out.println("(2) Play One Round");
System.out.println("(3) Player Win Statistics");
System.out.println("(4) Display Game Help");
System.out.println("(5) Exit Game");
System.out.println("Choose an option: ");
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 5) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
} catch (NumberFormatException e) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
switch (choice) {
case 1:
createNewPlayer(scanner);
break;
case 2:
guessNumber(scanner);
break;
case 3:
printStatistics();
break;
case 4:
printHelp();
break;
case 5:
exit = true;
}
}
scanner.close();
}
}
According to OO Design, the properties like gamesWon, gamesLost, totalWinnings and winPercent should be in the Player class only(Correct).
You have a parameterized Constructor which is same as Default or Zero parameterized Constructor. You have made no use of passing the name(String) as parameter as you are setting the name to "default" same string for every object irrespective of passed value.
Asking the user between from 1 to 100(choice) makes no sense as u have only 5 cases in switch.
You should not pass scanner object to other methods as It should be used only for scanning the data and close it immediately after use.
You can define a scanner object in which ever method you need it.
I have modified the constructor to accept the name.
public Player() {
Player("default");
}
public Player(String name) {
this.name = name;
this.winPercent = 0;
this.totalWinnings = 0;
this.gamesWon = 0;
this.gamesLost = 0;
}
Player is an object which consumes Game . So better to write the logic in Game and keep the Player as simple as possible.

Categories