Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method called countCoins that accepts a Scanner representing an input fi

ID: 3556917 • Letter: W

Question

Write a method called countCoins that accepts a Scanner representing an input file whose data is a series of pairs of tokens, where each pair begins with an integer and is followed by the type of coin, which will be pennies (1 cent each), nickels (5 cents each), dimes (10 cents each), or quarters(25 cents each), case-insensitively. Add up the cash values of all the coins and print the total money. For example, if the input file contains the following text:

3 pennies 2 quarters 1 Pennies 23 NiCkeLs 4 DIMES

For the input above, your method should produce the following output:

Total money: $2.09

Explanation / Answer

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

/**

* @author Casper

*

* http://answers.yahoo.com/question/index?qid=20120521134003AAiXLds

*

* Program : CoinCounter

* Sample input file content

* +++++++++++++BEGINNING OF FILE CONTENT+++++++++++++++++++++++

* 12 QUARTERS 1 Pennies 33

* PeNnIeS

*

* 10 niCKELs

* +++++++++++++END OF FILE CONTENT+++++++++++++++++++++++++++++

*/

public class CoinCounter

{

  private static final double MONEY_QUARTER = 0.25; // 25 Cents

  private static final double MONEY_DIME = 0.10; // 10 Cents

  private static final double MONEY_NICKEL = 0.05; // 5 Cents

  private static final double MONEY_PENNY = 0.01; // 1 Cent

  public double countCoins(Scanner inputStream)

  {

  double totalAmount = 0.0;

  int coinCount = 0;

  String coinType;

  while (inputStream.hasNext())

  {

coinCount = inputStream.nextInt();

coinType = inputStream.next();

  if (coinType.equalsIgnoreCase("QUARTERS"))

  {

totalAmount += MONEY_QUARTER * coinCount;

  }

  else if (coinType.equalsIgnoreCase("DIMES"))

  {

totalAmount += MONEY_DIME * coinCount;

  }

  else if (coinType.equalsIgnoreCase("NICKELS"))

  {

totalAmount += MONEY_NICKEL * coinCount;

  }

  else if (coinType.equalsIgnoreCase("PENNIES"))

  {

totalAmount += MONEY_PENNY * coinCount;

  }

  else

  {

  System.out

.println("Unrecognized coin type identified. String is "

  + coinType);

  }

  }

  return totalAmount;

  }

  public static void main(String[] args)

  {

Scanner userInputReader = new Scanner(System.in);

  System.out.println("Enter file name : ");

  try

  {

  System.out.println("Total money is : "

  + new CoinCounter().countCoins(new Scanner(new File(

userInputReader.next()))));

  } catch (FileNotFoundException e)

  {

  System.out.println("File Not Found.");

  }

  }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote