import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> my_array = new ArrayList<Integer>();
while (true) {
System.out.println("Enter your input to add to the list. Type in '-1' to finish adding. ");
int user_in = sc.nextInt();
if (user_in == -1) {
break;
} else {
my_array.add(user_in);
}
}
System.out.println(sort(my_array));
}
public static ArrayList<Integer> sort(ArrayList<Integer> arr) {
for (int i = 1; i < arr.size(); i++) {
int key = arr.get(i);
int j = i;
while (j > 0 && arr.get(j-1) > arr.get(j)) {
arr.set(j,arr.get(j-1));
j--;
}
arr.set(j,key);
}
return arr;
}
}
I tried running this program in my compiler and it won't work, I have no idea as to why because I double checked both the main method and the sort method that I created; the problem I have is that whenever the user tries to add an element to the ArrayList they will instantly lose their ability to enter the second input before the program closes and returns some value(in this case the arraylist). I don't understand why the program instantly finishes after the user inputs the first value because the while loop should make it continue if I'm not mistaken, so what am I doing wrong?
I tried running the program on multiple online compilers and visual studio code but to no avail, I even ran some tests with CHATGPT and the bot cannot find an issue with it which is why I'm confused. When I tried adding a continue statement in the while loop after the user inputs a value I got the same result.