299,464 views
36 votes
36 votes
In the U6_L2_Activity_Three class, write a public static method called hasDuplicates, which has a single parameter of an array of int values. The method should return a boolean which is true if the parameter array contains the same value more than once, and false otherwise. Use the runner class to test this method: do not add a main method to your code in the U6_L2_Activity_Three. Java file or it will not be scored correctly

User Keri
by
2.6k points

1 Answer

14 votes
14 votes

Answer:

Here is an implementation of the hasDuplicates method in the U6_L2_Activity_Three class:

import java.util.HashSet;

public class U6_L2_Activity_Three {

public static boolean hasDuplicates(int[] array) {

// Create a HashSet to store the values in the array

HashSet<Integer> set = new HashSet<>();

// Iterate through the array and add each value to the set

for (int value : array) {

if (set.contains(value)) {

// If the value is already in the set, return true

return true;

}

set.add(value);

}

// If no duplicates were found, return false

return false;

}

}

To test this method, you can use the Runner class like this:

public class Runner {

public static void main(String[] args) {

int[] array1 = {1, 2, 3, 4, 5};

int[] array2 = {1, 2, 2, 3, 4, 5};

int[] array3 = {1, 1, 2, 3, 4, 5};

System.out.println(U6_L2_Activity_Three.hasDuplicates(array1)); // should print false

System.out.println(U6_L2_Activity_Three.hasDuplicates(array2)); // should print true

System.out.println(U6_L2_Activity_Three.hasDuplicates(array3)); // should print true

}

}

Step-by-step explanation:

This will print false, true, and true to the console, indicating that the hasDuplicates method is working as expected.

User Sam Stokes
by
3.1k points