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
Other Requirements:
- create a
TokenGiverobject - store 10 tokens in it
- ask the
TokenGiverobject how many tokens it has and display the result - take 2 tokens out of the
TokenGiverobject - ask the
TokenGiverobject 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;
}
}
There is a better way, as Ed said. But with your assignment saying that you need a method to subtract exactly 1 Token, you are doing it how you should.
then you would could call GetToken(2);