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

Write a static method named countMoney that accepts as its parameter a Scanner f

ID: 3644046 • Letter: W

Question

Write a static method named countMoney that accepts as its parameter a Scanner for an input file whose data represents a person's money grouped into groups of bills. Your method should add up the cash values of all bills and print the total money at the end. The input consists of a series of pairs of tokens, where each pair begins with an integer and is followed by the type of bill, which will be either "bucks" (1 dollar each), "fives" (5 dollars each), "tens" (10 dollars each), "twenties" (20 dollars each), or

Explanation / Answer

import java.util.*;
import java.io.*;

public class money {

public static void main(String args[]) throws FileNotFoundException {
Scanner input = new Scanner(new File("c:\money.txt"));
while (input.hasNextLine()) {
countMoney(input.nextLine());
}
}

public static void countMoney(String input) {
int numberOfNotes = 0;
int totalAmount = 0;
String[] tokens = input.split(" ");

for (int i = 0; i < tokens.length; i++) {
if (i % 2 == 0) {
numberOfNotes = Integer.parseInt(tokens[i]);
} else {
if (tokens[i].equals("bucks")) {
totalAmount = totalAmount + (numberOfNotes * 1);
} else if (tokens[i].equals("fives")) {
totalAmount = totalAmount + (numberOfNotes * 5);
} else if (tokens[i].equals("tens")) {
totalAmount = totalAmount + (numberOfNotes * 10);
} else if (tokens[i].equals("twenties")) {
totalAmount = totalAmount + (numberOfNotes * 20);
} else if (tokens[i].equals("fifties")) {
totalAmount = totalAmount + (numberOfNotes * 50);
} else if (tokens[i].equals("hundreds")) {
totalAmount = totalAmount + (numberOfNotes * 100);
}
}
}
System.out.println("Total is:" + totalAmount);
}
}


In the above code, the split function is used to split the input string and make an array of strings out of it. Comparing strings should be with the .equals()
If you are using Java 7, you can use the switch statement instead of the if statements. Java 6 does not allow String type to be used in case statement.

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