Note that there are some explanatory texts on larger screens.

plurals
  1. POunexpected results when checking if two arrays are equals in Java
    text
    copied!<pre><code>import java.util.Scanner; import java.util.Arrays; class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the amount of numbers to be checked for sort"); int amount = input.nextInt(); int[] list = new int[amount]; for (int i = 0; i &lt; list.length; i++) { System.out.print("Enter a number: "); list[i] = input.nextInt(); } // Print the original array printArray(list); // list2 will contain the sorted list of elements int[] list2 = sortArray(list); printArray(list2); // Print the results if (Arrays.equals(list, list2)) { System.out.println("Already sorted!"); } else { System.out.println("Not sorted"); } } // Print array method public static void printArray(int[] array) { for (int i = 0; i &lt; array.length; i++) { System.out.println(array[i]); } } // function to sort the array public static int[] sortArray(int[] array) { boolean changed = true; do { changed = false; for (int i = 0; i &lt; array.length - 1; i++) { if (array[i] &gt; array[i + 1]) { // swap array[i] with array[i + 1] int temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; changed = true; } } } while (changed); return array; } } </code></pre> <p><strong>Original Question:</strong> <em>Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list.</em></p> <p><strong>My Question:</strong> <em>Why am I getting <strong>"Already sorted!"</strong> even when I enter an unsorted list?</em></p> <p><strong>Output when I run the program:</strong></p> <pre><code>gurbhej@Nanda:~/Dropbox/Programming/Java Programs/Test$ java Test Enter the amount of numbers to be checked for sort 5 Enter a number: 4 Enter a number: 3 Enter a number: 5 Enter a number: 6 Enter a number: 3 Unsorted 4 3 5 6 3 Sorted 3 3 4 5 6 Already sorted! gurbhej@Nanda:~/Dropbox/Programming/Java Programs/Test$ </code></pre>
 

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