Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>public class UniqueNumbers { public static void main(String[] args) { args = new String[6]; args[0] = "5"; args[1] = "6"; args[2] = "2"; args[3] = "5"; args[4] = "1"; args[5] = "1"; Arrays.sort(args); // Sort the array. This will use natural order: // low -&gt; high for integers, a -&gt; z and low to high for strings // Essentially this causes our array to sort from low to high, despite not being integers for (int i = 0; i &lt; args.length; i++) { // Loop over the entire array if (i == 0) { // (1) System.out.println(args[0]); } else if (!(args[i - 1].equals(args[i]))) { // (2) System.out.println(args[i]); } } } } </code></pre> <p>Output:</p> <pre><code>1 2 5 6 </code></pre> <p>Clarification:</p> <p>To make it easy to demonstrate, I've manually placed the values into the array. This makes no difference, you can just keep using your input method.</p> <p>(1): Read <code>(2)</code> first. Because of the method below, we would essentially skip the first element. The second part of the <code>else if</code> essentially means <code>if i &gt; 0</code>. If we wouldn't do this, we would get an <code>ArrayIndexOutOfBoundsException</code> when we do <code>args[i - 1]</code> because that would try to access <code>args[-1]</code>. That's why we skip the first element: to avoid this. However, this would also mean that our first value (<code>1</code>) would be ignored. That's why we just want to make sure the first value is always printed.</p> <p>(2): Now we check if the current element (<code>args[i]</code>) is equal (<code>.equals()</code>) to the previous elements (<code>args[i -1]</code>). If this is not the case (<code>!</code> inverts a statement), we print the current value.</p> <p>With this method, you can solve your assignment without any datastructures apart from the the standard one. </p> <p>More visualization:</p> <p>Start:</p> <pre><code>5 6 2 5 1 1 </code></pre> <p>Sort:</p> <pre><code>1 1 2 5 5 6 </code></pre> <p>Loop:</p> <pre><code>! 1 1 2 5 5 6 -&gt; Output: 1 ! 1 1 2 5 5 6 -&gt; Not different from previous one, no output ! 1 1 2 5 5 6 -&gt; Different from previous one, output: 1 2 ! 1 1 2 5 5 6 -&gt; Different from previous one, output 1 2 5 ! 1 1 2 5 5 6 -&gt; Not different from previous one, no output ! 1 1 2 5 5 6 -&gt; Different from previous one, output 1 2 5 6 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload