Implement in Java a class Coin that describes a coin with a name (e.g. dime) and
ID: 3541475 • Letter: I
Question
Implement in Java a class Coin that describes a coin with a name (e.g. dime) and a value (e.g. 10 cents).
Also implement a class Wallet that describes a collection of coins. Supply a method add() to add a coin to a purse, and a method printContent() that prints out to standard output the contents of a purse in the following format:
coinName (coinValue): numberOfCoins
Example
penny (1 cent): 11
dime (10 cents): 3
nickel (5 cents): 2
euro (100 eurocents): 5
In order to test your Wallet class you'll also implement a class WalletTest whose main() method does the following:
Constructs an empty wallet
Prompts the user to enter the name of a coin (e.g. dime), or an empty string to quit
Prompts the user to enter the value of a coin (e.g. 10 cents)
Adds the coin to the wallet
Prints the contents of the wallet
Goes to the 2nd bullet point above
Explanation / Answer
//Coin class
public class Coin {
private String coinName;
private int coinValue;
private int numberOfCoins;
public Coin(String coinName, int coinValue, int numberOfCoins)
{
this.coinName=coinName;
this.coinValue=coinValue;
this.numberOfCoins=numberOfCoins;
}
/**
* @return the coinName
*/
public String getCoinName() {
return coinName;
}
/**
* @param coinName the coinName to set
*/
public void setCoinName(String coinName) {
this.coinName = coinName;
}
/**
* @return the coinValue
*/
public int getCoinValue() {
return coinValue;
}
/**
* @param coinValue the coinValue to set
*/
public void setCoinValue(int coinValue) {
this.coinValue = coinValue;
}
/**
* @return the numberOfCoins
*/
public int getNumberOfCoins() {
return numberOfCoins;
}
/**
* @param numberOfCoins the numberOfCoins to set
*/
public void setNumberOfCoins(int numberOfCoins) {
this.numberOfCoins = numberOfCoins;
}
}
//Wallet class
import java.util.ArrayList;
import java.util.List;
public class Wallet {
List<Coin> coinsList = new ArrayList<Coin>();
public void add(Coin co)
{
coinsList.add(co);
}
public void printContent()
{
for(int i=0;i<coinsList.size();i++)
{
System.out.println(coinsList.get(i).getCoinName()+"("+ coinsList.get(i).getCoinValue() +"):"+coinsList.get(i).getNumberOfCoins());
}
}
}
//WalletTest class
import java.util.Scanner;
public class WalletTest {
public static void main(String args[])
{
Wallet wallt=new Wallet();
Scanner sin=new Scanner(System.in);
String name=null;
int value=0;
int numOfCoin=0;
while(true)
{
System.out.println("enter the name of a coin (e.g. dime), or an empty string to quit");
name=sin.nextLine();
if(name.isEmpty())
{
break;
}
System.out.println("enter the value of a coin");
value=sin.nextInt();
System.out.println("enter number of coins");
numOfCoin=sin.nextInt();
wallt.add(new Coin(name, value, numOfCoin));
wallt.printContent();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.