So I set up the basics. We need to create an array with the size specified by the user. Once the array has been made, the user has to populate the array with integer values. The program should then perform arithmetic operations as specified in the linked image at number 2. I made two more arrays, one to keep the answers for the sum, and one to keep the answers for the division. The problem now is, when you need to plus or divide the last number in the array, I get an IndexOutOfBoundsException because there is no value after the last one to plus or divide it with. They set it up so that it would through the exception as this lab is all about exceptions and making custom exceptions. However I need help making two exceptions. The first one is an exception for if the user enters a non integer value into the array. And the second one for the IndexOutOfBoundsException exception. I have no idea what to do. I'll add my code thus far below
import java.util.Scanner;
import java.util.Arrays;
public class Driver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int arrSize = 0;
int num = 0;
System.out.println("Enter array size");
arrSize = input.nextInt();
int[] numbers = new int[arrSize];
int[] sum = new int[arrSize];
int[] divide = new int[arrSize];
for (int i = 0; i < numbers.length; i++) {
System.out.println("Enter number");
num = input.nextInt();
numbers[i] = num;
}
for (int q = 0; q < numbers.length; q++) {
sum[q] = numbers[q] + numbers[q+1];
divide[q] = numbers[q] / numbers[q+1];
}
System.out.println(Arrays.toString(sum));
System.out.println(Arrays.toString(divide));
}
}
This should help you for scanning Integer values.
try{
System.out.print("Enter an integer: ");
int number = input.nextInt();
}
catch (InputMismatchException ex) {
System.out.println("Incorrect input: an integer is required)");
//It's also possible to throw your custom Exception here, like "throw new CustomException();"
}
About the IndexOutOfBoundsException, just write a try catch block around the area, where you expect that exception and throw your own custom exception.
try{
...
}catch(IndexOutOfBoundsException e){
throw CustomException2();
}