149k views
1 vote
Find a duplicate (10 points). Write a program FindDuplicate.java that reads n integer arguments from the command line into an integer array of length n, where each value is between is 1 and n, and displays true if there are any duplicate values, false otherwise.

User Fumihiko
by
5.4k points

2 Answers

4 votes

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");

}

}

}

Step-by-step 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

User Saloua
by
4.6k points
6 votes

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;

}

}

Step-by-step 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

User Mythagel
by
5.4k points