Write a method named isUnique that takes an array of integers as a parameter and
ID: 3541906 • Letter: W
Question
Write a method named isUnique that takes an array of integers as a parameter and that returns a boolean value indicating whether or not the values in the array are unique (true for yes, false for no). The values in the list are considered unique if there is no pair of values that are equal. For example, if a variable called list stores the following values:
Then the call of isUnique(list) should return true because there are no duplicated values in this list. If instead the list stored these values:
Then the call should return false because the value 3 appears twice in this list. Notice that given this definition, a list of 0 or 1 elements would be considered unique.
Explanation / Answer
Method
public boolean isUnique (int[] array){
boolean flag = true;
for (int i = 0; i < array.length; i++){
for (int j = i+1; j < array.length; j++)
if (i != j && array[i] == array[j]){
flag = false;
}
}
return flag;
}
}
In case if you would like to see the complete code, here it is
public class ArrayOfIntegers {
public static void main(String[] args) {
int[] list = {4, 7, 2, 3, 9, 12, -47, -19, 308, 3, 74};
ArrayOfIntegers arrayOfIntegers = new ArrayOfIntegers();
boolean flag = arrayOfIntegers.isUnique(list);
if (flag){
System.out.println(flag);
System.out.println("Yes, values in the array are unique");
}
else {
System.out.println(flag);
System.out.println("No, value in the array are not unique ");
}
}
public boolean isUnique (int[] array){
boolean flag = true;
for (int i = 0; i < array.length; i++){
for (int j = i+1; j < array.length; j++)
if (i != j && array[i] == array[j]){
flag = false;
}
}
return flag;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.