Answer to Question #289021 in Java | JSP | JSF for Hamza

Question #289021

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.


1
Expert's answer
2022-01-21T01:45:57-0500
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});
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog