user4833678
user4833678

Reputation:

Sorting array in an ascending array

When I try to sort the array, the result that I get is:

The sorted array is [0, 0, 0, 0, 0, 0, 0, 0]

The user fills the array with 8 numbers that should be eventually sorted. But what I'm getting is a bunch of 0s. Why am I getting 0s?

import java.util.Scanner;
import java.util.Arrays;

public class SortArray {

    public static void main(String[] args)
    {
        Scanner kbd = new Scanner(System.in);
        int[] numbers = new int[8];
        for(int i = 0; i < numbers.length; i++)
        {
            System.out.println("Enter the number for index " + i);
            int number = kbd.nextInt();
        }


        for(int i = 0; i < numbers.length; i++)
            for(int j = 1; j < numbers.length; j++)
            {
                if (numbers[i] > numbers[j]) 
                {
                    int temp = numbers[i];
                    numbers[i] = numbers[j];
                    numbers[j] = temp;
                }
            }
        System.out.println("The sorted array is " + Arrays.toString(numbers));
    }

}

Upvotes: 5

Views: 117

Answers (2)

matrixanomaly
matrixanomaly

Reputation: 6947

The issue is within these lines of code:

for(int i = 0; i < numbers.length; i++)
        {
            System.out.println("Enter the number for index " + i);
            int number = kbd.nextInt();
        }

Specifically int number = kbd.nextInt();

To add a little bit of explanation to Eran's answer, what you did in that line above is create a new variable number, and assign the value you get from the Scanner kbd. As you declare an int (meaning you write int on the left hand side) you're creating a variable that will hold an int value.

The main issue here is that right after you assign it to a variable called number, your loop closes and the variable is not used at all. It gets destroyed/removed/garbage-collected and the value is released. Next time you come around that loop again, a new variable called number is once again assigned with that value from the scanner.

Also notice now number and numbers are of different types, numbers is an array of ints, while number is just an int.

By changing int number to numbers[i], you're telling Java to assign the int received from the scanner kbd to the array numbers at position i. That way you don't lose the value and it gets saved inside the array, which is why when you print the array you no longer get all 0s. (the reason why you previously got all zeros is because you initialized an array of ints, but never given them values, so Java defaults to 0.

Upvotes: 1

Eran
Eran

Reputation: 393771

You are not assigning the user inputs to your array, which is why all the elements remain 0.

change

int number = kbd.nextInt();

to

numbers[i] = kbd.nextInt();

Upvotes: 4

Related Questions