Quindi sto creando un programma che prende un input int dalla riga di comando e quindi cerca l'array nel programma per l'int e, se trovato, restituisce l'indice del numero. In caso contrario, genera un'eccezione che indica che non è stata trovata e termina il programma. Questo è quello che ho finora:Utilizzo di try-catch con un ciclo if else
public static void main(String[] args) {
int[] intArray = {9, 97, 5, 77, 79, 13, 7, 59, 8, 6, 100, 55, 35, 89, 74, 66, 32, 47, 51, 88, 23};
System.out.println(Arrays.toString(intArray));
int intArgs = Integer.parseInt(args[0]);
System.out.println("Your entered: " + intArgs);
FindNum(intArray, intArgs);
}
public static int FindNum(int[] intArray, int intArgs) {
for (int index = 0; index < intArray.length; index++){
try{
if (intArray[index] == (intArgs))
System.out.println("Found It! = " + index);
else
throw new NoSuchElementException("Element not found in array.");
} catch (NoSuchElementException ex){
System.out.println(ex.getMessage());
}
}
return -1;
}
Mentre questo tipo di opere e in grado di trovare l'indice, si genera l'eccezione per ciascun numero nella matrice invece di uno solo per l'intero array. E se trova il numero nella matrice, allora sostituisce una delle linee con la riga di conferma dal ciclo. Uscita Esempio per 66:
[9, 97, 5, 77, 79, 13, 7, 59, 8, 6, 100, 55, 35, 89, 74, 66, 32, 47, 51, 88, 23]
Your entered: 66
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Found It! = 15
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Come si può fare in modo che quando trova il numero, viene stampato soltanto la linea indice e viceversa per l'eccezione. Sento che potrebbe avere qualcosa a che fare con il ciclo, ma non sono sicuro di cosa posso fare per evitarlo.
Inserire il ciclo all'interno del blocco try anziché inserire il try-block all'interno del ciclo. o meglio ancora, perché anche avere un blocco di prova? Basta fare la ricerca, e se non trovato, stampare il messaggio di errore. – FredK
Metti il tuo try-catch al di fuori del ciclo for, non al suo interno. – ManoDestra
si sta lanciando l'eccezione ogni volta per verificare il valore con un elemento nella matrice e trova una mancata corrispondenza, che è errata seno è possibile concludere l'elemento non in matrice solo dopo aver visitato tutti gli elementi. –