How to create an array that can be filled as long as the user enters numbers. Here's how I imagined it:

int n = 1; int[] arr = new int[n]; if (arr.length == 0) { n += 1; } 
  • one
    In this case, the semantics is better suited ArrayList - MBo

3 answers 3

If it is very rough, then it is (and do not forget to determine the code symbol to exit the input process, in this example, -1):

 int[] arr = new int[0]; int value; Scanner scanner = new Scanner(System.in); while ((value = scanner.nextInt()) != -1) { arr = Arrays.copyOf(arr, arr.length + 1); arr[arr.length - 1] = value; } 

Well, to get rid of this whole nightmare, various implementations of the List interface are used.

    In Java, arrays have a fixed size. ArrayList will suit you.

     ArrayList<Integer> array = new ArrayList<>(); while (smth) { array.add(sc.nextInt()); } 

      As the previous member of Naatsms answered, ArrayList really suits you. At the initial stage of learning Java, you can use a command line argument to enter user values ​​into an array as user input. But do not forget that if the array is integer (ArrayList a = new ArrayList <>;), then you must cast the command line argument to type int (or to the integer type that you use: int x = (int) args [0]; Moreover, the number of the element of the array is indicated in accordance with the number of the command line argument.