Instructions: Answer the following questions one at a time. After answering each question, check your answer (by clicking on the check-mark icon if it is available) before proceeding to the next question.
/**
* Calculates an array of percentages from an array of values.
*
* Specifically, this method calculates the total of all of the
* elements in the given array and divides each element into the
* total to determine the percentages.
*
* @param values The array of non-negative values
* @return The array of percentages.
*/
public static double[] toPercentages(double[] values)
{
}
toPercentages() method, looking for
trigger conditions that will cause it to fail.
What are the four obvious trigger conditions?
private static double[] sales;
public static void main(String[] args)
{
double[] percentages;
percentages = toPercentages(sales);
}
toPercentages() method
so that it specifies the NullPointerException.
What is the declaration now?
for loop in the
toPercentages() method so that it throws
an IllegalArgumentException if any element of
values is negative.
What statements are in the body of the loop now?
else clause in the
if statement?
toPercentages() method
so that it now also includes IllegalArgumentException.
What is the declaration now?
for loop, but before
the statement that allocates memory for result,
that throws an IllegalArgumentException
if total is 0.
What statement did you add?
toPercentages(double[]) method is now
implemented as follows.
public static double[] toPercentages(double[] values)
throws IllegalArgumentException, NullPointerException
{
double total;
double[] result;
// Calculate the total
total = 0;
for (int i=0; i<values.length; i++) // throws NullPointerException
{
if (values[i] < 0.0)
{
throw new IllegalArgumentException("Element " + i + " < 0");
}
total += values[i];
}
if (total <= 0.0)
{
throw new IllegalArgumentException("Total is 0");
}
// Allocate memory for the result
result = new double[values.length];
// Calculate the percentages
for (int i=0; i<values.length; i++)
{
result[i] = values[i] / total;
}
return result;
}
Why is the statement that allocates memory for result
where it is rather than earlier (for example right after the
declaration or even in the declaration statement)?
public class Example1
{
public static void main(String[] args)
{
int denominator, numerator, ratio;
numerator = 5;
denominator = 2;
ratio = numerator / denominator;
System.out.println("The answer is: "+ratio);
System.out.println("Done."); // Don't move this line
}
}
denominator to 0.
What runtime error message is now generated by this application?
try-catch statement to this application.
Specifically, put only the statement that generated the exception
inside of the try block and put no statments in the
catch block. (Hint: You should be able to determine
what exception to catch from the error message that you received
during the previous step. You should also be able to determine the line
number of the statemen that generated the exception if you didn't
change the white space.)
What statements are now in the body of the main()
method?
int denominator, numerator, ratio;
numerator = 5;
denominator = 0;
try
{
ratio = numerator / denominator;
System.out.println("The answer is: "+ratio);
}
catch (ArithmeticException ae)
{
System.out.println("Divide by 0.");
}
System.out.println("Done."); // Don't move this line
Will this version of the application compile? Why or why not?
catch block, add a call to the
printStackTrace() method of the
ArithmeticException object ae.
What is in the catch block now?
toPercentages() method in the
previous section, write a fragment that
calls toPercentages(), passing it the
array sales. If toPercentages() returns
normally, then the fragment must print each element. On the other
hand, if it returns "abnormally", then the fragment must
either call a method named reportInvalidSalesData()
or a method named reportNonexistentSalesData(),
as appropriate, passing sales in both cases.
What statements did you add?
public class Example2
{
public static void main(String[] args)
{
int ratio;
int[] numbers = {100,10,0,5,2,8,0,30};
try
{
for (int i=0; i < numbers.length-1; i++)
{
ratio = numbers[i] / numbers[i+1];
System.out.println(numbers[i]+"/"+numbers[i+1]+"="+ratio);
}
}
catch (ArithmeticException ae)
{
System.out.println("Couldn't calculate "+
numbers[i]+"/"+numbers[i+1]);
}
}
}
i (but do not initialize it) inside of
the try block, just before the for loop
as follows.
int i;
for (i=0; i < numbers.length-1; i++)
What error message are generated by compiling the application now?
i to the same statement that
declares ratio (but leave the initialization in the
for statement). What error message is generated by
compiling the application now?
i to be used before it is
initialized. Why is this error messaged generated anyway? (Hint:
Think about block statements.)
i before the
try block (so it will compile).
What output is generated by this application now?
Example2 so that it executes properly.
(Hint: Move the try-catch block inside of the
for block.) What is the body of the
main() method now?
public class Example3
{
public static void main(String[] args)
{
int i;
int[] data = {50, 320, 97, 12, 2000};
try
{
for (i=0; i < 10; i++)
{
System.out.println(data[i]);
}
}
catch (ArrayIndexOutOfBoundsException aioobe)
{
System.out.println("Done");
}
}
}
Example3 so that it loops "properly" and
does not need to use a try-catch statement. (Note: The output
should not change.) What is the body of the main()
method now?
toPercentages() method so that
it specifies (i.e., re-throws) NullPointerExceptions.
Is this the best way to handle this situation?
toPercentages() method so that
it checks for a null parameter but handles it with a
special return value.
return statements?
StringTokenizer
object provide?
StringTokenizer class?
String "5.3+9.2"?
import java.util.*;
public class Example4
{
public static void main(String[] args)
{
double leftOperand, result, rightOperand;
String leftString, operator, rightString;
StringTokenizer tokenizer;
tokenizer = new StringTokenizer(args[0], "+", true);
try
{
leftString = tokenizer.nextToken();
operator = tokenizer.nextToken();
rightString = tokenizer.nextToken();
leftOperand = Double.parseDouble(leftString);
rightOperand = Double.parseDouble(rightString);
if (operator.equals("+"))
result = leftOperand + rightOperand;
else
result = 0.0;
System.out.println("Result: " + result);
}
catch (NoSuchElementException nsee)
{
System.out.println("Invalid syntax");
}
catch (NumberFormatException nfe)
{
System.out.println("One or more operands is not a number");
}
}
}
String "5.3+"?
String "5.3+a"?
Copyright 2019