Skip to content

Lab 11: Spring Cleaning

It's that time of year again! After a long, cold winter, our text files are in need of some attention. For this exam, you will write a program that extracts and reformats all the numbers in a text file.

Learning Objectives

After completing this lab, you should be able to:

  • Construct and iterate elements of an ArrayList.
  • Use polymorphism to create and return objects.
  • Handle exceptions using try, catch, and throws.
  • Read the contents of a text file word by word.
  • Write the contents of a text file line by line.

Instructions

  1. Create a lab11 folder under src/labs.
  2. Download the provided files:
  3. Implement each method as described by the Javadoc comment.
  4. Test your program using JUnit (and feel free to add more tests).
  5. Submit SpringCleaning.java to Gradescope.

Optional Hints

First, try to solve problems on your own (with your partner or team). If you're stuck after several minutes, you can read the hints below. Ideally, each method should take less than 15 minutes.

  1. parseNumber()

    How can I tell if a number is a Double?

    Look for a decimal point in the string.

    How can I tell if a number is a BigInteger?

    Try to create an Integer object. A NumberFormatException will be thrown if the number is too big.

    How do I create Number objects?

    See the documentation for Integer, Double, and BigInteger.

    No really, how do I create the objects?
    • n = Integer.valueOf(str);
    • n = Double.valueOf(str);
    • n = new BigInteger(str);
  2. extractAll()

    What should I do with the FileNotFoundException?

    Nothing; the method throws FileNotFoundException, so you don't need to catch or do anything else.

    How do I read the file word by word?

    Use a Scanner. Call the hasNext() and next() methods in a while loop.

    What should I do with non-numbers?

    The parseNumber() method will throw a NumberFormatException. You can catch and ignore that exception.

  3. formatAll()

    How do I write the output file?

    Use a PrintWriter. Iterate over each number in the ArrayList using a for loop.

    How can I tell what format to use?

    The the number is an instance of Double, then you'll need to format with two decimal places. Both Integer and BigInteger are formatted the same way.

    What are the format specifiers?
    • For Double, you can use "%,.2f\n".
    • For Integer and BigInteger, you can use "%,d\n".