Concetti Chiave
- The program generates an array of 30 random integers between 0 and 99.
- Users are prompted to input a number to search for within the array.
- A binary search algorithm is used to determine if and how many times the number appears in the array.
- Invalid input is handled by a try-catch block that prompts for a valid number if a non-numeric character is entered.
- The program outputs whether the number is present and how many times it appears in the array.
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");
Organization and Research
for(int j=29;j>=0;j--)
for(i=0;i
if(v>v[j])
{
app=v;
v=v[i+1];
v[i+1]=app;
}//elementi del vettore ordinati
while((pdicotomica
{
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+" ");
}
}
Domande da interrogazione
- What is the primary function of the Array2 program?
- How does the program handle invalid user input?
- What method does the program use to search for the user's number in the array?
The Array2 program is designed to generate an array of 30 random integers between 0 and 99, prompt the user to input a number to search for within this array, and then determine if and how many times the number appears in the array using a binary search method.
The program uses a try-catch block to handle invalid input. If the user inputs a non-numeric character, the program catches the exception and prompts the user to enter a valid number between 0 and 99.
The program employs a binary search algorithm to efficiently locate the user's number within the sorted array. It calculates the middle index and adjusts the search range based on whether the middle element is greater or less than the target number.