package cap10.ricerca;

import IngressoUscita.Console;

public class Ricerca
{ static int ricerca(int val, int[] vec) throws Exception
  { boolean trovato = false;
    int i = 0;
    while (!trovato && (i < vec.length) && (vec[i] <= val))
    { if ((i > 0) && !(vec[i] >= vec[i - 1]))
        throw new Exception("Vettore non ordinato");
      if (vec[i] == val)
        trovato = true;
      else
        i++;
    }
    if (!trovato)
      throw new Exception("Valore non trovato");
    return i;
  }
  public static void main(String[] args)
  { Console.scriviStringa("Quanti elementi? ");
    int n = Console.leggiIntero();
    int[] vettore = new int[n];
    for (int i = 0; i < n; i++)
    { Console.scriviStringa("Elemento n. " + i + "? ");
      vettore[i] = Console.leggiIntero();
    }
    Console.scriviStringa("Valore da cercare? ");
    int valore = Console.leggiIntero();
    try
    { int posizione = ricerca(valore, vettore);
      Console.scriviStringa(
        "Valore trovato in posizione: " + posizione);
    }
    catch (Exception e)
    { Console.scriviStringa("Errore: " + e.getMessage());
    }
    Console.scriviStringa("Fine");
  }
}
