Exercise Set 2

Put your solutions under the set2 directory in your repository.

Don't forget to commit your changes locally and then push them up to GitLab.

Ex4

In a file named Ex4.java, write a program that computes and displays \(n!\), the factorial of an integer value \(n\).

Use a Scanner to read a value for \(n\) into an int variable. Use a for loop to compute the factorial, accumulating the result in another int variable. Run the program to discover what range of values you can use as input before it stops behaving correctly.

Optional: fix the problem by using a BigInteger object to accumulate the value for the factorial. You can import this class from the java.math package.

Ex5

In a file named Ex5.java, write a program that creates a temperature conversion table from Celsius to Fahrenheit. Your program should use a while loop to generate temperatures from 0.0°C to 36.0°C, in steps of 2.0°C. It should print Celsius temperatures in the first column and the corresponding Fahrenheit temperatures in the second column. All temperatures should be right-aligned and displayed to 1 decimal place. There should be appropriate column headings and borders.

Here's a partial example of what output should look like:

    +--------+--------+
    |   °C   |   °F   |
    +--------+--------+
    |   0.0  |  32.0  |
    |   2.0  |  35.6  |
    |   4.0  |  39.2  |
    |   6.0  |  42.8  |
    |   8.0  |  46.4  |
    |  10.0  |  50.0  |
    |  12.0  |  53.6  |

Remember that you can generate the degree symbol with the Unicode escape sequence \u00b0.

Don't overcomplicate this: it is possible to output each row of data in the table using a single call to System.out.printf.

Ex6

In a file named Ex6.java, write a program that analyses a line of text input by the user. Your program should display the total number of characters, the number of letters, the number of digits and the number of whitespace characters in this text.

Use the nextLine method of Scanner to read the line of text as a String object. The number of characters can be obtained by calling the length method on the string, and you can access its individual characters using the charAt method.

To test each character in the string, you can use the various static methods of the Character class. For example, Character.isDigit(c) will return true if the character c is a digit, false if it is not. See Section 4.3 of Liang's book and the API documentation for further details.

Here's an example of what you should see when running the program:

  $ java Ex6
  Enter a line of text: Java is 25 years old

  20 characters
  14 letters
  2 digits
  4 whitespace