Concetti Chiave
- The program initializes an array of 30 integers with random values between 0 and 99.
- It prompts the user to input a number to search for within the array, handling invalid input gracefully.
- The array is sorted in ascending order using a bubble sort algorithm for easier searching.
- A binary search is implemented to efficiently find the user-specified number in the sorted array.
- The program counts and displays the number of occurrences of the searched number or indicates if it is absent.
import java.io.*;
public class Array2
{
public static void main(String[] args)
{
InputStreamReader input = new InputStreamReader (System.in);
BufferedReader tastiera = new BufferedReader (input);
int v[] = new int[30];
int i=0,app=0,n=0,x=0,p=0,u=29,c=0,t=0;
for(i=0;i
v = (int) (Math.random()*100);
System.out.print("inserisci un numero da cercare compreso tra 0 e 99: ");
try
{
String NumeroLetto=tastiera.readLine();
n = Integer.valueOf(NumeroLetto).intValue();
}
catch(Exception e)
{
System.out.println("carattere non valido, inserire un numero compreso tra 0 e 99");
}
if(n
System.out.print("numero da ricercare non valido, inserire un numero compreso tra 0 e 99");
for(int j=29;j>=0;j--)
for(i=0;i
{
app=v;
v=v[i+1];
v[i+1]=app;
}//elementi del vettore ordinati
while((p
{
c=(p+u)/2;
if(v[c]==n)
{
t=1;
break;
}
if(v[c]>n)
p=c-1;
else
p=c+1;
}//fine ricerca dicotomica
for(i=0;i
if(v==n)
x+=1;
if(t==1)
{
if(x==1)
System.out.println("il numero "+n+" è presente "+x+" volta");
else
System.out.println("il numero "+n+" è presente "+x+" volte");
}
else
System.out.println("il numero "+n+" non è presente");
for(i=0;i
System.out.print(v+" ");
}
}