Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help with this question in Java, they are differant sub-part but don\'t g

ID: 3706327 • Letter: I

Question

I need help with this question in Java, they are differant sub-part but don't go togeather.

A. Write a method that searches a numeric array for a specified value. The method should return the subscript of the element containing the value if it is found in the array. If the value is not found, the method should throw an exception of the Exception class with the error message “Element not found”.

B. Write a statement that throws an IllegalArgumentException with the error message “Argument cannot be negative”.

C. Write an exception class that can be thrown when a negative number is passed to a method.

Explanation / Answer

(a) method that searches a numeric array for a specified value. The method should return the subscript of the element containing the value if it is found in the array. If the value is not found, the method should throw an exception of the Exception class with the error message “Element not found”.

public static int SearchArray( int[] array, int value)
throws Exception
{
int i; // Loop control variable
int element; // Element the value is found at
boolean found; // Flag indicating search results
// Element 0 is the starting point of the search.
i = 0;
// Store the default values element and found.
element = -1;
found = false;
// Search the array.
while (!found && i < array.length)
{
if (array[i] == value)
{
found = true;
element = i;
}
i++;
}
if (element == -1)
throw new Exception("Element not found.");
else
return element;
}

(B) Write a statement that throws an IllegalArgumentException with the error message “Argument cannot be negative”.

public class ExceptionArg{

public static void main(String args[])

{

int number;

String str;

try{

str="maya";

number = Integer.parseInt(str);

System.out.println("A");

}

catch(IllegalArgumentException e){

System.out.println("Argument cannot be negative");

}

}

}

(c) Write an exception class that can be thrown when a negative number is passed to a method

public class Negativenumb extends Exception
{
public Negativenumb()
{
super("Error: Negative number");
}

//below constructor accepts the number that caused the exception.
public Negativenumb(int n)
{
super("Error: Negative number: " + n);
}
}