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!
Hey guys I have been working on this program for class the past couple hours and just cant seem to get these last 2 issues resolved. Its basically a slightly modified CashRegister class with basic functions through a menu. The problems I am having are:
1) After the user makes a menu selection for the first time, every subsequent time the menu shows up in console twice and I cant seem to find a fix for this.
2) Also whenever I choose to display the content of my CashRegister, the first line is always output as 0.00 no matter the input.
Here is my CashRegister class followed by my tester:
import java.util.ArrayList;
/**
*
*/
/**
* #author Cole
*
*/
public class CashRegister {
private double dailyTotal;
private double totalPrice;
ArrayList<Double> items;
/**
Constructs a cash register with cleared item count and total.
*/
public CashRegister()
{
items = new ArrayList<Double>();
dailyTotal = 0;
totalPrice= 0;
}
/**
Adds an item to this cash register.
#param price the price of this item
*/
public void addItem(double price)
{
items.add(price);
dailyTotal = dailyTotal + price;
}
/**
Gets the price of all items in the current sale.
#return the total amount
*/
public double getTotal()
{
for(int x=0; x<items.size(); x++){
totalPrice = totalPrice + items.get(x);
}
return totalPrice;
}
/**
Gets the number of items in the current sale.
#return the item count
*/
public int getCount()
{
return items.size();
}
/**
Clears the item count and the total.
*/
public void clear()
{
items.clear();
totalPrice = 0;
}
public void display(){
for(int x=0; x<items.size(); x++){
System.out.printf("%10.2f%n", items.get(x));
}
System.out.println("------------------------------");
}
public double getDailyTotal(){
dailyTotal = dailyTotal + totalPrice;
return dailyTotal;
}
}
import java.util.ArrayList;
import java.util.Scanner;
/**
*
*/
/**
* #author Cole
*
*/
public class Prog2 {
/**
* #param args
*/
public static final String MENU = "******************************************\n" +
"* Enter \"n\" to start a new Cash Register. *\n" +
"* Enter \"a\" to add an item to the current Cash Register. *\n" +
"* Enter \"d\" to display the total of the current Cash Register. *\n" +
"* Enter \"e\" to exit the program. *\n" +
"******************************************";
public static final String NEW_CUSTOMER = "n";
public static final String ADD_ITEM = "a";
public static final String DISPLAY = "d";
public static final String EXIT = "e";
public static void main(String[] args) {
// TODO Auto-generated method stub
CashRegister register = new CashRegister();
Scanner keyboard = new Scanner(System.in);
String input;
double userInput = 0;
do {
input = printMenu(keyboard);
if(input.equals(NEW_CUSTOMER)){
register.getDailyTotal();
register.clear();
}
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
register.addItem(userInput);
userInput = keyboard.nextDouble();
}
else if(input.equalsIgnoreCase(DISPLAY)){
register.display();
System.out.println("Total: " + register.getTotal());
System.out.println("Item Count: " +register.getCount());
}
else if(input.equalsIgnoreCase(EXIT)){
System.out.printf("Daily Sales Total: " + "%.2f%n",register.getDailyTotal());
System.out.println("Program Ended...");
break;
}
}while(input != EXIT);
}
public static String printMenu(Scanner input){ //this method displays the menu for the user
String response = "no reponse yet";
System.out.println(MENU);
response = input.nextLine();
return response; //response returned based on the users input
}
}
You need to get input from the user before you add the item, that's why you are getting a 0 for your first item. Since your value for userInput is set to 0 at the beginning and your statements are switched you will always initialy create an item with 0.0 for it's value and all the other values will be one step behind the actual inputs.
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
userInput = keyboard.nextDouble();
register.addItem(userInput);
}
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.
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 have a lab for my Programming I class where we need to design a program that uses an ArrayList of resistances to calculate the total resistance of a parallel and series circuit. For the parallel circuit, I need to change every item in the ArrayList to its reciprocal (1/item). I got to this point and cannot seem to find why this is wrong and a possible way around it. Thanks.
**the error I get is "The method get(int) in the type ArrayList is not applicable for the arguments (double)" for the line " resistances = 1 / resistances.get(index);" **
-businesslogic class-
import java.util.ArrayList;
/**
* The class Circuit gathers the resistances of a user-defined number of
* resistors for a user-defined type of circuit and displays the total
* resistance of the circuit for the main method of the Presentation class.
*/
public class Circuit {
private double arrayListSize;
public double n;
public double sum;
public double finalSum;
public ArrayList<Double> resistances = new ArrayList<Double>();
/**
* #param initialPop
* user-defined initial population
*/
public final void setArraySize(final double alSize) {
arrayListSize = alSize;
}
public final double getArraySize() {
return arrayListSize;
}
public final void setResistors(double alResistances) {
for (n = 0; n < getArraySize(); n++) {
resistances.add(alResistances);
}
}
public ArrayList<Double> getResistors() {
return resistances;
}
public final void setPResistance(ArrayList<Double> resistances) {
for (double index : resistances) {
resistances = 1 / resistances.get(index);
}
sum = 0;
for (double i : resistances) {
sum =sum + i;
}
double finalSum = 1 / sum;
}
public final double getPResistance() {
return finalSum;
}
}
-presentation class-
import java.util.Scanner;
/**
* The Class Presentation
*/
public class Presentation {
/**
* The main class uses the Circuit class and user input
* to calculate the total resistance of a circuit.
*
* #param args
* command line arguments
*/
public static void main(final String[] args) {
Scanner keyboard = new Scanner(System.in);
Circuit resistanceTotal = new Circuit();
System.out.println("This program will calculate the"
+ " total resistance of either a parallel or "
+ " a series circuit.\n");
System.out.println("Would you like to calculate the"
+ " resistance of a parallel circuit (1) or a"
+ " series circuit (2)?");
int userChoice = keyboard.nextInt();
System.out.println("How many resistors are there in the circuit?");
resistanceTotal.setArraySize(keyboard.nextDouble());
System.out.println("Enter resistance of resistor #" + (resistanceTotal.n + 1));
resistanceTotal.setResistors(keyboard.nextDouble());
resistanceTotal.getResistors();
if (userChoice == 1) {
resistanceTotal.setPResistance(resistanceTotal.getResistors());
resistanceTotal.getPResistance();
}
if (userChoice != 1 & userChoice != 2) {
System.out.println("You must enter 1 or 2!!!");
}
keyboard.close();
}
}
Your error is in this the setPResistance method. The method arrayList.get(i) takes a int value as a parameter, and you passed it the actual value of the position, which is a double.
To replace each item in the arraylist to its reciprocal, change the method like so:
public final void setPResistance(ArrayList<Double> resistances) {
for (int c = 0; c < resistances.size(); c++) {
resistances.set(c, 1/resistances.get(c));
}
}
Java docs on the set(int index, Double element) method:
Replaces the element at the specified position in this list with the
specified element.