I have the following assignment for homework.
Requirements
- design a class called
TokenGiver
with the following elements:- a default constructor, a parametrized constructor that takes an
int
- a method that adds a specified number of tokens to the number of tokens
- a method that subtracts exactly ONE token from your number of tokens
- a method that returns the number of tokens in your object
- a default constructor, a parametrized constructor that takes an
Other Requirements:
- create a
TokenGiver
object - store 10 tokens in it
- ask the
TokenGiver
object how many tokens it has and display the result - take 2 tokens out of the
TokenGiver
object - ask the
TokenGiver
object how many tokens it has and display the result
Question
Is there a better way to subtract two tokens at once from my Main()
method, or is calling the GetToken()
method twice the only way?
Code Snippet:
using System;
class Program
{
const int NUM_TOKENS = 10;
static void Main()
{
TokenGiver tokenMachine = new TokenGiver(NUM_TOKENS);
Console.WriteLine("Current number of tokens = {0}",
tokenMachine.CountTokens());
tokenMachine.GetToken();
tokenMachine.GetToken();
Console.WriteLine("New number of tokens = {0}",
tokenMachine.CountTokens());
Console.ReadLine();
}
}
class TokenGiver
{
private int numTokens;
public TokenGiver()
{
numTokens = 0;
}
public TokenGiver(int t)
{
numTokens = t;
}
public void AddTokens(int t)
{
numTokens += t;
}
public void GetToken()
{
numTokens--;
}
public int CountTokens()
{
return numTokens;
}
}