Intent: The program is intended to recieve an input from the user and compare it against the contents of the ArrayList. If the input is not found, the program the input to the list and gives it a winCount of 1. The list is printed with the number of wins following it. In the end the user with the hightest wincount wins. If there is a tie a user is randomly selected.
The problem: My arrayValues are not properly stored
The Team class has been provided with the methods below :
public class Team implements Comparable<Team> {
// _-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_
// CS 1323: Implement this method
/**
* This is the method you will fix to allow you to return the contents of
* this Team item in the nice format: "name: winCount". The current
* implementation will allow the program to compile, but it returns nothing.
*
* For example: "Sooners: 3"
*
* #return the formatted String that can then be output to the console.
*/
public String toString(String team, int wins) {
String winStatement = team + ": " + wins;
return winStatement;
}
// _-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_
// Data fields
private String name;
private int winCount;
Team() {
name = "Sooners";
winCount = 1;
}
Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
// ----------------------------------------------------
// Getters and Setters (aka Accessors and Mutators) ===
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the winCount
*/
public int getWinCount() {
return winCount;
}
/**
* #param winCount
* the winCount to set
*/
public void setWinCount(int winCount) {
this.winCount = winCount;
}
/**
* Increments the winCount variable by one for this Team
*/
public void incrementWinCount() {
winCount++;
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object.
*
* This method allows you to use the contains method in ArrayList to see
* if any element in an array list has the same name as a specific Team.
*
* #param o
* the other Team being compared to.
*/
#Override
public boolean equals(Object o) {
return name.equals(((Team) o).name);
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object
*
* #param otherTeam
* one team
*/
public boolean sameName(Team otherTeam) {
return name.equals(otherTeam.name);
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object
*
* #param team1
* one team
* #param team2
* the other team
*/
public static boolean sameName(Team team1, Team team2) {
return team1.name.equals(team2.name);
}
/**
* This method allows you to sort an ArrayList of Team items using
* Collections.sort
*
* #param o
* the other Team being compared to.
* #return -1 if this Team item should come first, +1 if this Team item
* should come after the other, and 0 if this Team item is
* equivalent to the other.
*/
#Override
public int compareTo(Team o) {
if (this.winCount < o.winCount) {
return -1;
} else if (this.winCount > o.winCount) {
return 1;
}
return 0;
}
}
I am new to reference variables and ArrayLists, so I suspect the error has something to do with them. The code is below :
public class Project6_ReeceWitcher
{
public static void main(String args[])
{
Scanner scnr = new Scanner(System.in);
Random rando = new Random();
String name = "hi";
int cycles = 0;
int value = 0;
ArrayList<Team> teams = new ArrayList<Team>();
Team myTeam = new Team();
Team thisTeam = new Team(name);
System.out.println("Welcome to the Advanced Sportsball Tracker!");
while (!name.equals("x")) // looping print statement
{ // x loop begins
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
if (!teams.equals(name))
{
teams.add(thisTeam);
myTeam.setWinCount(1);
}
else if (teams.equals(name))
{
myTeam.incrementWinCount();
}
cycles++;
}// x loop ends
if (cycles == 1) // prints no data if user immediately exits
{
System.out.println("No data input");
}
System.out.println("Final Tally: "); // loop to print teams
for (Team team : teams) // FIXME
{
System.out.println(team);
}
The program runs and outputs these values
Welcome to the Advanced Sportsball Tracker!
Which team just won? (x to exit)
1
Which team just won? (x to exit)
2
Which team just won? (x to exit)
x
Final Tally:
Team#75b84c92
Team#75b84c92
Team#75b84c92
The winner is the with win(s)
However the intended output is
Welcome to the Advanced Sportsball Tracker!
Which team just won? (x to exit)
Sooners - these values are user inputs and are not printed
Which team just won? (x to exit)
Sooners -
Which team just won? (x to exit)
Cowboys -
Which team just won? (x to exit)
Bears -
Which team just won? (x to exit)
Bears -
Which team just won? (x to exit)
Cowboys -
Which team just won? (x to exit)
ThatOtherTeam -
Which team just won? (x to exit)
x
Final Tally:
ThatOtherTeam: 1
Sooners: 2
Cowboys: 2
Bears: 2
The winner is the Cowboys with 2 win(s)!
Thank you for the assistance!
Related
I tried so hard but I couldn't get this to work. My method "guess" in class "Game" should compare the parameter "someInt" with the variable "x" from the class "Number". I would really appreciate any help, I have to get this done this evening. This is what I got, so far:
public class Number
{
private int x;
/**
* Constructor for class Number.
* This constructor assigns x to a new random
* number between 1 and 100
*/
public Number()
{
// The following lines creates a random number
// between 1 and 100 and assigns it to x
java.util.Random random = new java.util.Random();
x = random.nextInt(100) + 1;
}
public int getNumber(){
return x;
}
}
And my other class:
public class Game
{
private Number number;
/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
number1.getNumber(x);
}
/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < x){
System.out.println("Your guess is too small");
}
else if (someInt > x) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}
Here is a modified version
public class Game
{
private Number number;
/**
* This constructor should initialize the filled number
*/
public Game() {
this.number = new Number();
}
/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < number.getNumber()){
System.out.println("Your guess is too small");
}
else if (someInt > number.getNumber()) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}
On the other hand, you shouldn't use classes with the same names as in java.lang, as Number. It's distracting, making your code hard-readable and bug-genic.
The problems were:
Number.getNumber() does not take arguments, you provided one
You created a local object number1 while you should be operating on number.
In guess(), you used x, instead, Number.getNumber() should be used.
I recommend renaming Number to something not causing name clashes with java.lang.Number.
You have number1.getNumber(x); , but getNumber in your number class has no arguments.
In your getNumber method you have a return of x. You need to handle it in game like:
int numberToCompare; (declare below private Number number)
number1.getNumber(x); must be numberToCompare = number1.getNumber();
then you need to compare someint with numberToCompare.
this here is wrong:
public Game() {
Number number1 = new Number();
number1.getNumber(x);
}
because Number.getNumber() takes no param and must return an int (it is a GETTER)...
maybe you meant to do:
public class Game {
private int x;
private Number number;
/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
this.x = number1.getNumber();
}
I need to program a cash register that can perform transactions.
A transaction has the following steps:
(1) The transaction starts when the customer decides to purchase an item for a given price.
(2) The customer give the cashier a certain amount of money in bills and coins.
(3) The cashier calculates the exact change. The change is
calculated so that the total number of bills and coins given to the customer is minimized.
(4) The cashier gives the customer their change and the remaining
bills and coins are added to the register.
If the transaction must be cancelled for any reason, the cash
register returns to the state before the transaction began.
According to Web-Cat, 85% of my coding is correct. I am really struggling with the last part of my code which include public void completePurchase() and public static String prettyPrint(int amount) { }. My instructor has included small descriptions above all the methods.
I really hope that you can help me with these two methods. Certainly, I am not asking for solutions, but help to solve the problem.
The first class includes the cashregister.class. And the second class is a Junittester.
> public class CashRegister
{
// ==========================================================
// Constants
// ==========================================================
/** The value of a dollar (100 cents) */
public static final int DOLLAR = 100;
/** The value of a quarter (25 cents) */
public static final int QUARTER = 25;
/** The value of a dime (10 cents) */
public static final int DIME = 10;
/** The value of a nickel (5 cents) */
public static final int NICKEL = 5;
/** The value of a penny (1 cent) */
public static final int PENNY = 1;
// ==========================================================
// Fields
// ==========================================================
private int purchasePrice;
private int[] registerMoney;
private int[] paymentMoney = { 0, 0, 0, 0, 0 };
private int[] changeMoney = { 0, 0, 0, 0, 0 };
private int transactionCount; // number of
// transactions
private int transactionTotal; // number of cents
// that I have made from transactions
// ==========================================================
// Constructors
// ==========================================================
/**
* Creates a new CashRegister object with the specified money in it. If the
* specified money array is not valid, an IllegalArgumentException is
* thrown. The money array is not valid if: - the length of the array is
* anything but 5 - the array contains a negative number in any of the cells
* - the array contains a 0 in _all_ of its cells /**
*
* #param money
* the money that will go into the new cash register
*/
public CashRegister(int[] money)
{
if (this.moneyHasNegative(money))
{
throw new IllegalArgumentException();
}
transactionCount = 0;
transactionTotal = 0;
purchasePrice = 0;
registerMoney = Arrays.copyOf(money, money.length);
}
/**
* #param money
* money has a negative integer.
*/
private boolean moneyHasNegative(int[] money)
{
if (money.length != 5)
{
return true;
}
if (money[0] < 0 || money[1] < 0 || money[2] < 0 || money[3] < 0
|| money[4] < 0)
{
return true;
}
if (money[0] == 0 && money[1] == 0 && money[2] == 0 && money[3] == 0
&& money[4] == 0)
{
return true;
}
return false;
}
// ==========================================================
// Public Accessor Methods
// ==========================================================
/**
* Returns the purchase price. Returns 0 if a purchase has not begun yet.
*
* #return purchase price.
*/
public int getPrice()
{
return purchasePrice;
}
/**
* #return the registerAmount
*/
public int getRegisterAmount()
{
return registerMoney[0] * DOLLAR + registerMoney[1] * QUARTER
+ registerMoney[2] * DIME + registerMoney[3] * NICKEL
+ registerMoney[4] * PENNY;
}
/**
* The value of payment amount multiplied by constants.
*/
private int paymentAmountValue()
{
return paymentMoney[0] * DOLLAR + paymentMoney[1] * QUARTER
+ paymentMoney[2] * DIME + paymentMoney[3] * NICKEL
+ paymentMoney[4] * PENNY;
}
// ----------------------------------------------------------
/**
* #return the amount of payment.
*/
public int getPaymentAmount()
{
return this.paymentAmountValue();
}
/**
* The value of change amount multiplied by constants.
*/
private int changeAmountValue()
{
return changeMoney[0] * DOLLAR + changeMoney[1] * QUARTER
+ changeMoney[2] * DIME + changeMoney[3] * NICKEL
+ changeMoney[4] * PENNY;
}
/**
* #return the change amount.
*/
public int getChangeAmount()
{
return this.changeAmountValue();
}
/**
* #return the register money as string.
*/
public String getRegisterMoney()
{
return "Dollars: " + registerMoney[0] + "\n" + "Quarters: "
+ registerMoney[1] + "\n" + "Dimes: " + registerMoney[2] + "\n"
+ "Nickels: " + registerMoney[3] + "\n" + "Pennies: "
+ registerMoney[4] + "\n";
}
/**
* get the payment money as a string.
*/
private String paymentMoneyString()
{
return "Dollars: " + paymentMoney[0] + "\n" + "Quarters: "
+ paymentMoney[1] + "\n" + "Dimes: " + paymentMoney[2] + "\n"
+ "Nickels: " + paymentMoney[3] + "\n" + "Pennies: "
+ paymentMoney[4] + "\n";
}
/**
* #return the payment money as a string.
*/
public String getPaymentMoney()
{
return this.paymentMoneyString();
}
/**
* The value of payment amount multiplied by constants.
*/
private String changeMoneyString()
{
return "Dollars: " + changeMoney[0] + "\n" + "Quarters: "
+ changeMoney[1] + "\n" + "Dimes: " + changeMoney[2] + "\n"
+ "Nickels: " + changeMoney[3] + "\n" + "Pennies: "
+ changeMoney[4] + "\n";
}
/**
* #return the change money as a string.
*/
public String getChangeMoney()
{
return this.changeMoneyString();
}
/**
* #return the transaction count.
*/
public int getTransactionCount()
{
return transactionCount;
}
/**
* #return the transaction in total.
*/
public int getTransactionTotal()
{
return transactionTotal;
}
// ==========================================================
// Public Mutator Methods
// ==========================================================
// Begins a transaction using the specified price.
// If a transaction is already in progress, throws an IllegalStateException
// If the specified price is not positive, throws an
// IllegalArgumentException
// ----------------------------------------------------------
/**
* Begins a transaction using the specified price.
*
* #param price
* the price of the item
*/
public void beginPurchase(int price)
{
if (transactionAlreadyInProgress())
{
throw new IllegalStateException();
}
if (price <= 0)
{
throw new IllegalArgumentException();
}
purchasePrice = price;
}
/**
* shows that the transaction is already in progress.
*/
private boolean transactionAlreadyInProgress()
{
return false;
}
// Records the specified payment.
// If the purchase has not begun yet, throws IllegalStateException
// If the specified money array is not valid (see the constructor),
// throws IllegalArgumentException
// If the amount of money given is not sufficient to cover the
// purchase price, the transaction is canceled.
// ----------------------------------------------------------
/**
* Records the specified payment.
*
* #param money
* payment money
*/
public void enterPayment(int[] money)
{
if (purchaseHasNotBegunYet())
{
throw new IllegalStateException();
}
if (this.notValidMoneyArray(money))
{
throw new IllegalArgumentException();
}
while (true)
{
if (money[0] != purchasePrice || money[1] != purchasePrice
|| money[2] != purchasePrice || money[3] != purchasePrice
|| money[4] != purchasePrice)
break;
}
paymentMoney = Arrays.copyOf(money, money.length);
}
/**
* purchase has not begun. Purchase will be canceled if true.
*/
private boolean purchaseHasNotBegunYet()
{
return false;
}
/**
* If money array or length is not valid, it will return false.
*/
private boolean notValidMoneyArray(int[] money)
{
if (money.length != 5)
{
return true;
}
if (money[0] < 0 || money[1] < 0 || money[2] < 0 || money[3] < 0
|| money[4] < 0)
{
return true;
}
if (money[0] == 0 && money[1] == 0 && money[2] == 0 && money[3] == 0
&& money[4] == 0)
{
return true;
}
{
return false;
}
}
// Calculates the change due to the customer using the largest bill
// and coin denominations first. Thus, the change given will use the
// maximum amount of dollars, then the maximum amount of quarters,
// then dimes, then nickels, then pennies. For example, if the change
// required is $15.84, the change will be 15 dollars, 3 quarters,
// 1 nickel, and 4 pennies. It will NOT be 12 dollars, 8 quarters,
// 10 dimes, 12 nickels and 24 pennies. If payment has not been entered
// yet, throws IllegalStateException.
// ----------------------------------------------------------
/**
* throws out the calculated change.
*
* #param money
* changeMoney
*/
public void calculateChange()
{
int changeToGiveBack = 1299;
int dollarsToGiveBack = 0;
int quartersToGiveBack = 0;
int dimesToGiveBack = 0;
int nickelsToGiveBack = 0;
int penniesToGiveBack = 0;
changeMoney[0] = dollarsToGiveBack;
changeMoney[1] = quartersToGiveBack;
changeMoney[2] = dimesToGiveBack;
changeMoney[3] = nickelsToGiveBack;
changeMoney[4] = penniesToGiveBack;
while (changeToGiveBack >= DOLLAR)
{ // check if >= works better or worse than >
changeMoney[0] = changeMoney[0] + 1;
changeToGiveBack = changeToGiveBack - DOLLAR;
}
while (changeToGiveBack >= QUARTER)
{
changeMoney[1] = changeMoney[1] + 1;
changeToGiveBack = changeToGiveBack - QUARTER;
}
while (changeToGiveBack >= DIME)
{
changeMoney[2] = changeMoney[2] + 1;
changeToGiveBack = changeToGiveBack - DIME;
}
while (changeToGiveBack >= NICKEL)
{
changeMoney[3] = changeMoney[3] + 1;
changeToGiveBack = changeToGiveBack - NICKEL;
}
while (changeToGiveBack >= PENNY)
{
changeMoney[4] = changeMoney[4] + 1;
changeToGiveBack = changeToGiveBack - PENNY;
}
if (paymentNotBeenEntered())
{
throw new IllegalStateException();
}
}
// Completes the transaction. Money in cash register is updated.
// The price, payment, and change all become 0. The transaction count
// is incremented and the total amount of money made in all transactions
// is updated. If the cashier does not have enough money to give change
// in the EXACT way it was calculated, the transaction is cancelled -
// the item is not purchased, and the customer gets their exact coins back.
// The amount and type of money in the register is unchanged from before
// the transaction began. If change has not been calculated yet,
// throws IllegalStateException
private boolean paymentNotBeenEntered()
{
return false;
}
/**
* Completes the transaction.
*
* #param money
* complete purchase money
*/
public void completePurchase()
{
}
// ==========================================================
// Public Static Methods
// ==========================================================
// Returns a string for the specified amount with a dollar sign
// at the beginning and a decimal two places from the end.
// For example, the amount 10538 cents becomes the string $105.38.
// No commas are printed in the string.
// public static String prettyPrint(int amount) { }
// ==========================================================
// Private Methods
// ==========================================================
// In this project you WILL have private methods. If you do not,
// it means you have redundant code in your class and the grader
// will take off points for it.
}
This is the part where CashregisterTest begins.
> public class CashRegisterTest
{
private CashRegister cr;
// ----------------------------------------------------------
/**
* throws an Exception
*
* #throws Exception
*/
#Before
public void setUp()
throws Exception
{
cr = new CashRegister(new int[] { 20, 20, 20, 20, 20 });
}
// ----------------------------------------------------------
/**
* Testing the Constructors
*/
// ==========================================================
// Constructor Tests
// ==========================================================
#Test
public void testConstructor()
{
assertEquals(2820, cr.getRegisterAmount());
cr.beginPurchase(1299);
assertEquals(1299, cr.getPrice());
int[] paymentMoney = { 30, 0, 0, 0, 0 };
cr.enterPayment(paymentMoney);
assertEquals(paymentMoney, cr.getPaymentAmount());
cr.calculateChange();
assertEquals(1288, cr.getChangeAmount());
assertEquals(0, cr.getChangeAmount());
assertEquals(0, cr.getTransactionCount());
assertEquals(0, cr.getTransactionTotal());
}
// ----------------------------------------------------------
/**
* Checks if constructor throws an illegal argument exception when array !=
* 5.
*/
// This test method checks that the constructor
// correctly throws an illegal argument exception when
// the array has a length other than five
#Test(
expected = IllegalArgumentException.class)
public void testConstructorArrayBadLength()
{
int[] money = { 20, 20, 20, 20 }; // bad parameter; only has length four
cr = new CashRegister(money); // this should throw an exception
fail(); // if we reach here, our constructor is wrong
}
// ----------------------------------------------------------
/**
* Test if the constructor throws illegal argument exception if array
* contains a negative integer.
*/
// Write a test method that checks if the constructor
// correctly throws an illegal argument exception when
// the array argument contains a negative integer
#Test(
expected = IllegalArgumentException.class)
public void testConstructorArrayNegativeLength()
{
int[] money = { -20, 20, 20, 20, 20 }; // bad parameter; only has
// length
// four
cr = new CashRegister(money); // this should throw an exception
fail(); // if we reach here, our constructor is wrong
}
// Write a test method that checks if the constructor
// correctly throws an illegal argument exception when
// the array argument contains all zeros
// ----------------------------------------------------------
/**
* Tests if the constructor correctly throws an illegal argument Exception
* when array = 0.
*
* #Test IllegalArgumentException
*/
#Test(
expected = IllegalArgumentException.class)
public void testConstructorArrayAllZeros()
{
int[] money = { 0, 0, 0, 0, 0 }; // bad parameter; only has length four
cr = new CashRegister(money); // this should throw an exception
fail(); // if we reach here, our constructor is wrong
}
// ==========================================================
// Accessor Tests
// ==========================================================
// ----------------------------------------------------------
/**
* Dont know yet
*/
#Test
public void testGetMoney()
{
// getRegisterMoney
// getPaymentMoney
// getChangeMoney
String registerMoney =
"Dollars: 20\n" + "Quarters: 20\n" + "Dimes: 20\n"
+ "Nickels: 20\n" + "Pennies: 20\n";
String zeroMoney =
"Dollars: 0\n" + "Quarters: 0\n" + "Dimes: 0\n"
+ "Nickels: 0\n" + "Pennies: 0\n";
assertEquals(registerMoney, cr.getRegisterMoney());
assertEquals(zeroMoney, cr.getPaymentMoney());
assertEquals(zeroMoney, cr.getChangeMoney());
}
// ==========================================================
// Mutator Tests
// ==========================================================
// ----------------------------------------------------------
/**
* Place a description of your method here.
*/
// ----------------------------------------------------------
/**
* Sunny day not yet
*/
#Test
public void testSunnyDay()
{
System.out.println(cr.getRegisterMoney());
cr.beginPurchase(1800);
assertEquals(1800, cr.getPrice());
int[] paymentMoney = { 30, 0, 0, 0, 0 };
cr.enterPayment(paymentMoney);
System.out.println(cr.getPaymentMoney());
cr.calculateChange();
System.out.println(cr.getChangeMoney());
// cr.completePurchase();
System.out.println(cr.getRegisterMoney());
String registerMoney =
"Dollars: 20\n" + "Quarters: 20\n" + "Dimes: 20\n"
+ "Nickels: 20\n" + "Pennies: 20\n";
assertEquals(registerMoney, cr.getRegisterMoney());
}
// ==========================================================
// Static Method Tests
// ==========================================================
}
completePurchase:
If change has not been calculated yet throws IllegalStateException
That's easy enough to check, I'll leave that to you.
If the cashier does not have enough money to give change in the EXACT way it was calculated, the transaction is cancelled - the item is not purchased, and the customer gets their exact coins back.
Iterate through each type of coin, and subtract the amount in change from the amount in the registers. If any go below zero, then give the customer back their money.
for (int x = 0; x < registerMoney.length; x++)
if (registerMoney[x] - changeMoney[x] < 0)
// GIVE ME BACK MY MONEY!
If you make it past here, then there is enough change of each type in the register, so go ahead with the transaction.
Money in cash register is updated.
for (int x = 0; x < registerMoney.length; x++)
registerMoney[x] -= changeMoney[x];
The price, payment, and change all become 0. The transaction count is incremented and the total amount of money made in all transactions is updated.
This is fairly straight-forward Java stuff. You can fill the paymentMoney and changeMoney arrays with zero like so:
Arrays.fill(array, 0);
And that's all there is to it! I hope that helps.
By the way, your instructor is teaching you bad habits. Other classes should not have to know about the internal state of a cash register in order to make a purchase; they should just be able to call the method 'Purchase' and have everything happen in one go.
I missed points for putting implementation in the driver class, rather than having the driver class only make calls methods in other classes. I'm not sure how to move the implementation outside of the main class. Suggestions welcome!
/*
*Deitel Chapter 6 Exercise 6.30
*/
package guess;
import java.util.Scanner;
/**
*Driver class for number guessing game
*/
public class GuessDriver {
/**
*
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/*
*instantiate guess class
*/
Guess Guess = new Guess();
/*
*loops program until user guesses correct number
*/
while (Guess.getGuess() != Guess.secretNumber){
/*
*takes input from user
n*/
System.out.println("Enter a number from 1 to 1000: ");
int setGuess = input.nextInt();
Guess.setGuess(setGuess);
/*
*nested if-else statements compares guess against secret number
*/
if(Guess.secretNumber < Guess.guess){
System.out.println("too high");
} else if (Guess.secretNumber > Guess.guess){
System.out.println("too low");
} else {
System.out.println("Congratulations, you win!");
}
}
}
}
/*
*Deitel Chapter 6 Exercise 6.30
*/
package guess;
import java.util.Random;
/**
* Takes in and stores an integer, sets value for random number
*/
public class Guess {
/**
*instance variable
*/
public int guess;
/**
*instance variable
*/
public int secretNumber = (int) (Math.random() * 999 + 1);
/**
*return secret number
* #return
*/
public int getSecretNumber() {
return secretNumber;
}
/**
*return guess
* #return
*/
public int getGuess() {
return guess;
}
/**
*set guess
* #param guess
*/
public void setGuess(int guess) {
this.guess = guess;
}
}
Well, first of all. I would suggest to make private all variables of the Guess class. (See that you have a getSecretNumber() method that already gives you the value of the secretNumber variable.
Secondly, you could create a public method like checkGuessing(int guess) in the Guess class. This method would take the user input, and write the answer on console ("too high", "too low", and so on).
Another option could be to add this same functionality to the setGuess method.
Finally, to ease future debugging, you should name the classes with Uppercase letters, the variables (even the instances of classes) with camelCase letters, and try that class's variables be named different than the name of the class.
So the final code could be something like this:
in GuessDriver class:
package guessdriver;
import java.util.Scanner;
/**
*Driver class for number guessing game
*/
public class GuessDriver {
/**
*
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/*
*instantiate guess class
*/
Guess guess = new Guess();
/*
*loops program until user guesses correct number
*/
while (guess.checkGuessing()==false){
/*
*takes input from user
n*/
System.out.println("Enter a number from 1 to 1000: ");
int setGuess = input.nextInt();
guess.setGuess(setGuess);
}
}
}
And in the Guess class:
package guessdriver;
public class Guess {
/**
*instance variable
*/
private int guessing;
/**
*instance variable
*/
private int secretNumber = (int) (Math.random() * 999 + 1);
/**
*return secret number
* #return
*/
public int getSecretNumber() {
return secretNumber;
}
/**
*return guess
* #return
*/
public int getGuess() {
return guessing;
}
/**
*set guess
* #param guess
*/
public void setGuess(int guessing) {
this.guessing = guessing;
}
public boolean checkGuessing(){
if(secretNumber < guessing){
System.out.println("too high");
return false;
} else if (secretNumber > guessing){
System.out.println("too low");
return false;
} else {
System.out.println("Congratulations, you win!");
return true;
}
}
}
Okay, the objective of this program is to input String values, such as penny, dime, quarter, and nickel, into the ArrayList purse in class Purse. Then once Purse is executed through the PurseMain class then the Coin class is supposed to take the string values of the coin names that were added into the ArrayList purse and add their dollar values together. My professor told us to create the coin values in a third Class called Coin and to create another ArrayList in PurseMain. But really my main question is, how do you call the objects that were created in the Coin Class into the ArrayList in PurseMain? Any help would be appreciated. Thanks.
package purse;
import java.util.Scanner;
import java.util.ArrayList;
/**
* The Purse program creates an ArrayList called purse that gets printed out,
reversed, and transfered into another ArrayList called purse2.
*
* - ArrayList purse
* - ArrayList purse2
* - Scanner coin - the Scanner that is used to type the contents of ArrayList purse
* - Scanner coin2- the Scanner that is used to type the contents of ArrayList purse2
* - String input - contains Scanner coin and is used to fill ArrayList purse
* - String input2- contains Scanner coin2 and is used to fill ArrayList purse2
* - String end - sentinel for ending the process inputting strings into Scanner coin and Scanner coin2
*
*/
public class Purse
{
ArrayList<String> purse = new ArrayList<>();
/**
* fills ArrayList purse and purse2 with U.S coin names
* purse gets printed out and then again is printed in reverse
* purse2 is printed
*/
public void addCoin()
{
String penny = "penny";
String nickel = "nickel";
String dime = "dime";
String quarter = "quarter";
String end = "done";
Scanner coin = new Scanner (System.in);
String input = " ";
System.out.println("Please put as many coins of U.S currency as you like into the purse, hit the ENTER button after each coin and, type 'done' when finished: ");
while (!input.equalsIgnoreCase ("done"))
{ input = ( coin.nextLine());
if (input.equalsIgnoreCase("penny")||input.equalsIgnoreCase("nickel")||input.equals IgnoreCase("dime")||input.equalsIgnoreCase("quarter")||input.equalsIgnoreCase(en d))
{
purse.add(input);
purse.remove(end);
}
else{
System.out.println("Please input a coin of U.S currency.");
}
}
}
/**
#return ArrayList purse
*/
public ArrayList<String> printPurseContents()
{
System.out.println("Contents of the purse: " + purse);
return purse;
}
/** checks whether purse2 has the same coins in the same order as purse
* #return
* #param purse2
*/
public boolean sameContents(Purse purse2)
{
if (purse2.purse.equals(purse))
{
return true;
}
else
{
return false;
}
}
/**
* checks whether purse2 has the same coins as in purse, disregarding the order
* #param purse2
* #return
*/
public boolean sameCoins(Purse purse2)
{
if( purse2.purse.containsAll(purse))
{
return true;
}
else
{
return false;
}
}
/**
* adds contents of purse into purse2 and clears purse of its contents
* #param purse2
*/
public void transfer(Purse purse2)
{
purse2.purse.addAll(purse);
purse.clear();
System.out.println("The second purse now has: " + purse2.purse );
System.out.println("and the first purse has: " + purse);
}
}
----------PurseMain
package purse;
import java.util.ArrayList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**legalcoin = new ArrayList<Coin>; <-----
* legalcoin.add( new Coin ("Penny", .01); <--- Professor said to do
*
* #author
* 9/01/2015
* Lab I
*/
public class PurseMain
{
private ArrayList<Coin> legalCoin = new ArrayList<>();
legalCoin.add (new Coin ("Penny",0.01));
public static void main(String[] args)
{
Purse purse1 = new Purse();
purse1.addCoin();
purse1.printPurseContents();
Purse purse2 = new Purse();
purse2.addCoin();
purse2.printPurseContents();
System.out.println("Both of the purses have the same contents and the contents is in the same order: " + purse2.sameContents(purse1));
System.out.println("Both of the purses have the same contents: " +purse2.sameCoins(purse1));
}
}
----------Coin
package purse;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/** private string name;
* private double value;
* sum up value method
*
* #author
*/
public class Coin
{
private String Penny = "penny";
private String Nickel = "nickel";
private String Dime = "dime";
private String Quarter = "quarter";
private double penny = 0.01;
private double nickel = 0.05;
private double dime = 0.10;
private double quarter = 0.25;
public void SumUpValue()
{
}
}
You will need to have a new Coin pouch in your purse(requirement wise). So, have a coin pouch that takes list of coins in it. Since the purse has the coin pouch, it would be a property of your purse.
public class Coin{
private String type;
private String currencyType;
//more fields and getters and setters
}
public class Purse{
ArrayList<String> purse = new ArrayList<>();
List<Coins> coinPouch = new ArrayList<>();//contains coin objects
.
.
.
.
private void addCoins(String coinType){
Coin coin = new Coin();
coin.setType(coinType);
coinPouch.add(coin);
}
}
Your modified code for adding coins would be like:
if (input.equalsIgnoreCase("penny")|| input.equalsIgnoreCase("nickel") ||input.equalsIgnoreCase("dime")||input.equalsIgnoreCase("quarter")||input.equalsIgnoreCase(end)){
addCoins(input);//Adds coins to the list of coins objects and the purse now has the coin pouch :D
purse.remove(end);
}
else{
System.out.println("Please input a coin of U.S currency.");
}
I'm creating a small 'game' program where a player enters a floor/room number, but when the player guess it gets stuck and loops on a single player and doesn't move to the next player and doesn't tell if the player is correct or incorrect as a guess where the dog is being held in the building.
PuppyPlay.java:
import java.util.Random;
import java.util.Scanner;
/**
* This program is used as a driver program to play the game from the
* class LostPuppy.
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
*/
public class PuppyPlay{
/**
* Driver program to play LostPuppy.
*
* #param theArgs may contain file names in an array of type String
*/
public static void main(String[] theArgs){
Scanner s = new Scanner(System.in);
LostPuppy game;
int totalFloors;
int totalRooms;
int floor;
int room;
char[] players = {'1', '2'};
int playerIndex;
boolean found = false;
Random rand = new Random();
do {
System.out.print("To find the puppy, we need to know:\n"
+ "\tHow many floors are in the building\n"
+ "\tHow many rooms are on the floors\n\n"
+ " Please enter the number of floors: ");
totalFloors = s.nextInt();
System.out.print("Please enter the number of rooms on the floors: ");
totalRooms = s.nextInt();
s.nextLine(); // Consume previous newline character
// Start the game: Create a LostPuppy object:
game = new LostPuppy(totalFloors, totalRooms);
// Pick starting player
playerIndex = rand.nextInt(2);
System.out.println("\nFloor and room numbers start at zero '0'");
do {
do {
System.out.println("\nPlayer " + players[playerIndex]
+ ", enter floor and room to search separated by a space: ");
floor = s.nextInt();
room = s.nextInt();
//for testing, use random generation of floor and room
//floor = rand.nextInt(totalFloors);
//room = rand.nextInt(totalRooms);
} while (!game.indicesOK(floor, room)
|| game.roomSearchedAlready(floor, room));
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
} while (!found);
playerIndex = (playerIndex + 1) % 2;
System.out.println("Great job player " + players[playerIndex] +"!");
System.out.println("Would you like to find another puppy [Y/N]? ");
} while (s.nextLine().equalsIgnoreCase("Y"));
}
}
LostPuppy.java:
import java.util.Random; // Randomize the dog placement in building
import java.util.Scanner; // User input
/**
* This program is used as a program to play the game from the
* driver PuppyPlay.java
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
*/
public class LostPuppy{
private char[][] myHidingPlaces; // Defining class fields for assignment
private int myFloorLocation;
private int myRoomLocation;
private char myWinner;
private boolean myFound;
/**
* Creates constructor takes floor/room numbers inputted by user
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public LostPuppy(int theFloors, int theRooms) {
Random random = new Random();
myHidingPlaces = new char[theFloors][theRooms];
// Filling array with spaces
int i;
for (i = 0; i < theFloors; i++) {
for (int k = 0; k < theRooms; k++) {
myHidingPlaces[i][k] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
/**
* Checks if room has been searched prior
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean roomSearchedAlready(int theFloors, int theRooms) {
boolean searchedRoom;
if (myHidingPlaces[theFloors][theRooms] == ' ') {
myHidingPlaces[theFloors][theRooms] = 'S';
searchedRoom = false;
} else {
searchedRoom = true;
}
return searchedRoom;
}
/**
* Checks if the puppy has been found
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean puppyLocation(int theFloors, int theRooms) {
if (myHidingPlaces[myFloorLocation][myRoomLocation] == myHidingPlaces[theFloors][theRooms]) {
myFound = true;
} else {
myFound = false;
}
return myFound;
}
/**
* Checks if floors and rooms won't throw out of bounds error
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean indicesOK(int theFloors, int theRooms) {
boolean indicesFit;
if (theFloors < numberOfFloors() && theRooms < numberOfRooms()) {
indicesFit = true;
} else {
indicesFit = false;
}
return indicesFit;
}
/*
* Checks # of floors and returns it
*/
public int numberOfFloors() {
return myHidingPlaces.length;
}
/*
* Checks # of rooms and returns it
*/
public int numberOfRooms() {
return myHidingPlaces[0].length;
}
/**
* Checks which player found the dog and won, or if not checks to see what player
* guessed wrong and puts their # in the box
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
* #param thePlayer for 1st or 2nd player
*/
public boolean searchRoom(int theFloors, int theRooms, char thePlayer) {
if (myHidingPlaces[myFloorLocation][myRoomLocation] == myHidingPlaces[theFloors][theRooms]) {
myFound = true;
myWinner = thePlayer;
} else {
myHidingPlaces[theFloors][theRooms] = thePlayer;
myFound = false;
}
return myFound;
}
/*
* toString displays the current hidingPlaces array and it’s contents EXCEPT
* the location of the puppy which remains hidden until he/she is found at
* which point toString will be called (by the driver) and both the player
* who found the puppy and a ‘P’ will be displayed in the same cell….
*
*
*
*/
public String toString() {
return null;
}
}
To run this code you'll need to put both codes with their respective posted names and run PuppyPlay.java with LostPuppy.java in the same folder FYI.
The problem lied in this place in PuppyPlay:
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
So your program expect you to input something here, and it will keep waiting until you press enter, so you can just remove that line: s.nextLine();