Homework 4: Methods and Testing


  • Organize input/output code into multiple methods.
  • Write methods to compute mathematical functions.

Exercise 4.1   Output Utility

In the previous chapter, you learned how to format numbers in a variety of ways using System.out.printf. Format specifiers like "%-10.1f" and "%0,3d" can be difficult to read and understand, especially if they're used over and over again in a program. For convenience, we can write methods that take care of these details.

As as starting point, download OutputUtil.java. It contains stubs for three methods: printMoney, printTime, and main. Each method has a Javadoc comment (see Appendix B) that explains what it should do. Implement the print methods using one line of code each. In the main method, call printMoney and printTime (twice each) to produce the following output: (note CHF stands for Swiss Francs.)

3.45 CHF

Neither of the print methods should display a newline character, so that they can be called in the middle of a sentence. For this exercise, the main method will print newlines after each method call.

Your solution must only use printf to display output. Autolab will automatically reject submissions that call print or println. Your solution must also NOT use the + operator. For this exercise, Autolab will reject submissions that have a "+" character anywhere in the file.

Exercise 4.2   Input Utility

In the previous chapter, you learned how to read input using a Scanner. It's very common to prompt the user for something, read the next line of input, and store the results in a variable. We can simplify this process by writing methods.

As as starting point, download InputUtil.java. It contains stubs for three methods: inputLine, inputDouble, and main. Each method has a Javadoc comment (see Appendix B) that explains what it should do.

In the main method, call inputDouble and inputLine to produce the following output (based on user input in this color):

Give me a double: 3.14159
You entered: 3.14159
Give me a line: Think Java!
You entered: Think Java!

Note that the input methods automatically append ": " to each prompt. This design allows you to have a consistent formatting whenever you ask for user input.

Notice also that inputDouble automatically prevents the "Scanner bug" (see Chapter 3) when inputting a mix of numbers and text. Your main method should NOT call any Scanner methods.


Exercise 4.3   Unit Conversion

When solving physics problems, you often need to convert from one unit to another. Define a class named Convert that has the following six methods. Each method should be public and static, return a double value, and have a double parameter.

  • fromCelsiusToFahrenheit
  • fromFahrenheitToCelsius
  • fromKilometersToMiles
  • fromMilesToKilometers
  • fromMetersPerSecondToMilesPerHour
  • fromMilesPerHourToMetersPerSecond

For each method, write an appropriate Javadoc comment (see Appendix B). Each comment should include (1) a one-sentence description explaining what the method does, (2) an @param tag that describes the parameter, and (3) an @return tag that describes the return value.

In contrast to previous exercises, the Convert class should NOT have a main method. Instead, create a separate file named Test.java with a mainmethod that calls the Convert methods. You will only submit Convert.java, so feel free to format the test output however you like. For example:

double c = 10.0;
double f = Convert.fromCelsiusToFahrenheit(c);
System.out.printf("%.1f C = %.1f F\n", c, f);

Note that f = (9/5 * c) + 32 and c = 5/9 * (f - 32), where f denotes a temperature in degrees Fahrenheit and c denotes a temperature in degrees Celsius. Also, there are 1.60934 kilometers per mile, 1000 meters per kilometer, and 3600 seconds per hour.

Exercise 4.4   Math Tricks

Define a class named MathTricks that has the following three methods:

  • public static double logOfBase(double b, double x)

    Computes "log base b of x" using the Change-of-Base Formula.

  • public static double sphereVolume(double radius)

    Calculates the volume of a sphere with the given radius.

  • public static double normalPDF(double mu, double sigma, double x)

    Evaluates the probability density function (at point x) for a normal distribution(equation 1 on that page) -


    , given the mean (mu) and standard deviation (sigma).

The purpose of this exercise is to gain experience with the Math class. See if you can write the first two methods using one line of code each. The last method is more complex, so it helps to break it down into multiple lines. Use the Math.exp method to raise e to a power.

Exercise 4.5   Phone Number

Countries participating in the North American Numbering Plan use 10-digit phone numbers. To make phone numbers easier to read, we often put a dash after the 3rd and 6th digits (e.g., 202-456-1414).

Define a class named PhoneNumber that provides the following two methods:

  • public static void print(long number)

    Prints the given integer formatted as a phone number.

  • public static int check(long number)

    Returns the sum of the last four digits of the number, e.g.: for the phone number 123-456-7890, 7 + 8 + 9 + 0 = 24

Notice that phone numbers need to be declared as long integers, since the maximum int is 2,147,483,647. In Java source code, long integers need to end with the capital letter L. For example, the phone number 987-654-3210 would be 9876543210L.

The purpose of this exercise is to practice extracting digits from an integer using modulo. Your solution must NOT use String methods (Chapter 6). Autolab will automatically reject submissions containing words like charAt, substring, and toString.


Submissions for all problems for HW4 should be made to https://autolab.cs.jmu.edu 


Back to Top