(a public String getName() public Class getSupClass()

advertisement
Question 4 [JVM] [2*5 marks]
(a) What are the three sub processes in linking in JVM?



Verification
Preparation
Resolution
(b) Explain, with the help of an example, one method in the class java.lang.Class.
public String getName()
public Class getSupClass()
public boolean isInterface()
public Class[] getInterfaces()
public Method[] getMethods()
public Fields[] getFields()
public Constructor[] getConstructors()
Question 5 [Exceptions] [15 marks]
Write a Java 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 non-positive value for N, then an exception should be thrown and caught with the
message “N must be positive”. If there is any exception as the user is entering the N numbers,
an error message should be displayed and the user prompted to enter the number again.
import java.util.Scanner;
public class Question5Average
{
public static void main(String[] args)
{
// Variable declarations
Scanner scan = new Scanner(System.in);
int n = 0;
int sum = 0;
double average;
boolean error;
// Loop until there is no error
do
{
try
{
error = false;
// Assume no error
System.out.println("How many numbers do you want to enter?");
n = scan.nextInt();
if (n <= 0 ) throw new Exception("Number must be greater than 0.");
}
catch (Exception e)
// Catch any exception and print the error message
{
error = true;
// Set error flag if an exception occurs
System.out.println(e.getMessage());
}
} while (error);
// Loop through each number and calculate the average
for (int i=0; i<n; i++)
{
// Repeat input as long as there is an error
do
{
try
{
error = false; // Assume no error
System.out.println("Enter number " + (i+1));
int num = scan.nextInt();
sum += num;
}
catch (Exception e)
{
// Set error flag if an exception occurs
error = true;
System.out.println("Error, please enter the number again.");
// Read newLine remaining from nextInt
String temp = scan.nextLine();
}
} while (error);
}
average = (double) sum / n;
System.out.println("\nThe average is " + average);
}
} // Question5Average
Question 6 [Recursion] [15 marks]
One way for finding the maximum of an array of integers is to divide the array into two
halves, find the maximum m1 in the first half and m2 in the second half through recursive
calls, and then return the larger of m1 and m2. Write the method in Java using the following
heading: public static int findMax(int[] a, int start, int end)
public static int findMax(int[] a, int start, int end)
{
if ( !(start < end) ) return a[start];
int mid = (start + end) / 2;
int max1 = findMax(a, start, mid);
int max2 = findMax(a, mid+1, end);
if (max1 > max2)
return max1;
else
return max2;
}
Download