Respuesta :
Answer:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
System.out.print("Enter the array size: ");
n = input.nextInt();
int[] numberArray = new int[n];
System.out.print("Enter the numbers between 1 and " + n + ":");
for(int i=0; i<n; i++){
numberArray[i] = input.nextInt();
}
System.out.println(findDublicate(numberArray, n));
}
public static boolean findDublicate(int[] numberArray, int n){
boolean flag = false;
for (int i = 0; i < n; i++) {
for (int j = i + 1 ; j < n; j++) {
if (numberArray[i] == numberArray[j]){
flag = true;
break;
}
}
}
return flag;
}
}
Explanation:
Inside the function:
- Check if there are duplicates by comparing each number in the array using nested for loop
Inside the main:
- Ask the user for array size and the numbers
- Put them into the array called numberArray
- Call the function and print the result
Answer:
import java.util.Arrays;
import java.util.Random;
public class FindDuplicate {
public static void main(String[] args) {
// Declare an array of size n
// assume n=10
int n=10;
boolean duplicate =true;
int [] intArray = new int[n];
Random rand = new Random();
//Reading n values into the array using a for loop
for(int i=1; i<n; i++){
intArray[i]= rand.nextInt(11);
}
System.out.println(Arrays.toString(intArray));
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(intArray[i] == intArray[j]) {
duplicate = true;
break;
}
}
}
if(duplicate){
System.out.println("True");
}
else{
System.out.println("False");
}
}
}
Explanation:
Using Java programming language
An Array is declared of size n =10
Using the Random class random integers from 1-10 inclusive are generated and loaded into the array (using a for loop)
To find duplicate elements, two for loops are used. The first loop (outer) iterates through the array and selects an element, The inner loop is used for comparison of the selected element with other elements in the array.
If there is a match, the boolean variable duplicate will be set to true
And True is printed to the screen, else False is printed