Task #4: Arrays and Methods
In this task, you are being asked to write a method that manipulates arrays in Java.
Write a method called printUnique that accepts one integer array as argument, and
print all unique elements form the array.
You may use the following header for this method:
static void printUnique(int[] array)
For example, if you pass {2, 4, 2, 15, 4, 5, 6, 9, 12, 2} to this method, then
the method should print 15, 5, 6, 9, 12 as unique elements.
NOTE: Declare and initialize the array without taking input from user.
1. Create a program called ArrayPrintUniqueLab2.java.
2. Correctly display appropriate messages.
public class ArrayPrintUniqueLab2 {
static void printUnique(int[] array) {
for (int i = 0; i < array.length; i++) {
boolean unique = true;
for (int j = 0; j < array.length; j++) {
if (i != j && array[i] == array[j]) {
unique = false;
break;
}
}
if (unique) {
System.out.print(array[i] + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
printUnique(new int[]{2, 4, 2, 15, 4, 5, 6, 9, 12, 2});
}
}
Comments
Leave a comment