Question

This method adds an integer to an array. I have to figure out how to do a try catch for the input to catch negative integers and things like letters, and i can't figure out how to do it. How would i do this?

private static int[] addInt (int[] ara, Scanner kb) {
   int[] newAra = new int[ara.length + 1];
   for(int i = 0; i < ara.length; i++) {
      newAra[i] = ara[i];
      }
   System.out.println("Enter new integer:");
   newAra[newAra.length-1] = kb.nextInt();
   selectionSort(newAra);
   return newAra;
   }
Was it helpful?

Solution

int does support negative numbers. If you want to have an exception for negative numbers, you have to generate it yourself. Your code will only throw a InputMismatchException from the Scanner class which will being thrown up if the next token in the scanner doesn't match with the regular expression for integer, with other words; at characters.

Here below is an example of throwing an exception for negative numbers for your method

int value = kb.nextInt();
if (value < 0) throw new IllegalArgumentException();
else newAra[newAra.length-1] = kb.nextInt();

and in your code,

try {
    my_int_array = addInt(my_int_array, scanner);
}
catch (InputMismatchException ime) {
     // tell that it's not a digit - number
}
catch (IllegalArgumentException iae) {
     // tell that it's a negative input
}
catch (Exception e) {
     // to catch all other exceptions from the Scanner class like IllegalStateException ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top