javasortingjava.util.scanner

How to Correctly Capture and Sort a Dynamic Set of Input Numbers in Java?


I'm working on a Java application that requires the user to input 5 numbers, which the program will then sort. My current implementation uses the Scanner class to read the numbers, but I'm facing issues with both capturing the input correctly and sorting the numbers thereafter.

Here's the code I've written so far:

import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int[] arr = new int[5];

            System.out.print("Please enter 5 numbers: ");
            for(int i = 0; i < arr.length; i++) {
                arr[i] = scanner.nextInt();
            }

            // Display the unsorted array
            System.out.print("Array before sorting: ");
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }

            // Insertion sort algorithm
            for (int i = 1; i < arr.length; i++) {
                int key = arr[i];
                int j = i - 1;

                while (j >= 0 && arr[j] > key) {
                    arr[j + 1] = arr[j];
                    j = j - 1;
                }
                arr[j + 1] = key;
            }

            // Display the sorted array
            System.out.println("\nArray after sorting: ");
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
        }
    }
}

While attempting to run this program, I noticed a couple of issues:

Input Handling: The program does not correctly capture the 5 numbers input by the user. It seems like my loop or the use of Scanner.nextInt() might be incorrect. How can I ensure the user's input is accurately captured into the array?

Sorting Logic: Although I intended to implement an insertion sort for the array, I'm not confident that it's working as expected. After sorting, the numbers don't appear in the correct order. Is there an issue with my sorting logic?

Output Repetition: In my attempt to display the sorted and unsorted arrays, I mistakenly repeated the input capture. How can I correctly display the contents of the array before and after sorting?

Lastly, I'm relatively new to using Scanner for input and would appreciate any tips or best practices for its use, especially in the context of this problem.


Solution

  • You should write

    try(Scanner scanner = new Scanner(System.in))
    {
        [Code]
    }
    catch(chosenException name, optionalOtherException otherName)
    {
        [Code]
    }
    

    With try-catch, you prevent the program from crashing when something is wrong (like a String input when an Integer value is expected). When you want to check not for a specific type of exception, but for any exception possible, write catch(Exception name).

    At for(int i = 0; 1< arr.length; i++), there is a mistake: You wrote 1<arr.length. 1 will always be 1, so the loop will continue forever (since the length of the array is 5). I assume you wanted to write i<arr.length. Also, I think it's unnecessary to write arr.length; you can as well write length.

    At System.out.print(arr[i] = scanner.nextInt());: why do you assign the values a second time? You already did so in the loop above. If you want to print the values you assigned to the array in the loop above, remove the = scanner.nextInt() part and write only System.out.print(arr[i]). However, I recommend writing either System.out.println(arr[i]) or System.out.print(arr[i] + "SomeString"), otherwise there will be nothing between two numbers. For example, the numbers 6,2,3,8,9 will be printed 62389 without any spaces, line breaks or other characters between.