I am trying to sort some user-entered integers, separated by spaces.
Entrance: 4 2 1 5 9 - Expected result: 1 2 4 5 9
I can’t figure out how to stop the loop after the user presses the input in the loop where I <Num. My code works when I enter integers one by one. Any help would be appreciated
class javasort {
public static void main(String[] args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);
num = 5;
int array[] = new int[num];
System.out.println("Enter integers: ");
for (i = 0; i < num; i++)
array[i] = Integer.parseInt(input.next());
num = i;
for (i = 0; i < (num - 1); i++) {
for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}}
source
share