Java Reference
In-Depth Information
Programming Projects
Visit
www.myprogramminglab.com
to complete select exercises online and get instant
feedback.
1. Write a program that calculates the average of
N
integers. The program should
prompt the user to enter the value for
N
and then afterward must enter all
N
numbers. If the user enters a nonpositive value for
N
, then an exception should be
thrown (and caught) with the message “
N
must be positive.” If there is any excep-
tion as the user is entering the
N
numbers, an error message should be displayed,
and the user prompted to enter the number again.
2. Here is a snippet of code that inputs two integers and divides them:
Scanner scan =
new
Scanner(System.in);
int
n1, n2;
double
r;
n1 = scan.nextInt();
n2 = scan.nextInt();
r = (
double
) n1 / n2;
Place this code into a
try-catch
block with multiple catches so that different
error messages are printed if we attempt to divide by zero or if the user enters tex-
tual data instead of integers (
java.util.InputMismatchException
). If either of
these conditions occurs, then the program should loop back and let the user enter
new data.
3. Modify the previous exercise so that the snippet of code is placed inside a method.
The method should be named
ReturnRatio
, read the input from the keyboard,
and throw different exceptions if there is a division by zero or an input mismatch
between text and an integer. Create your own exception class for the case of divi-
sion by zero. Invoke
ReturnRatio
from your
main
method and catch the excep-
tions in
main
. The
main
method should invoke the
ReturnRatio
method again
if any exception occurs.
4. (This is a version of an exercise from Chapter 5.) Programming Project 5.2 from
Chapter 5 asked you to create a class named
Fraction
. This class is used to
represent a ratio of two integers. It should include mutator functions that allow
the user to set the numerator and the denominator along with a method that
displays the fraction on the screen as a ratio (e.g., 5/9). Modify the class so that
it throws the exception
DenominatorIsZeroException
if the denominator is set
to zero. Do not forget to account for the constructors! You will have to create the
DenominatorIsZeroException
class and it should be derived from
Exception
.
Write a
main
method that tests the new
Fraction
class, attempts to set the
denominator to zero, and catches the
DenominatorIsZeroException
exception.
5. Write a program that converts dates from numerical month/day/year format to nor-
mal “month day, year” format (for example, 12/25/2000 corresponds to December
25, 2000). You will define three exception classes, one called
MonthException
,
another called
DayException
, and a third called
YearException
. If the user enters
VideoNote
Solution to
Programming
Project 9.1