1

I have a integer array named numbers and a int named number. How can I insert the value of number into numbers? Assuming i can't just do numbers[0] = number;

int[] numbers;
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
Hagelsnow
  • 45
  • 4
  • 2
    Well, first you would have to initialize the array with a fixed size. Do you know the size beforehand? Also, why can't you do `numbers[0] = number;`? – OH GOD SPIDERS Nov 17 '21 at 10:17
  • 2
    in this case you may want to use arraylist, because the size of the array you want is dynamic. use `ArrayList numbers = new ArrayList<>();` – Issa Khodadadi Nov 17 '21 at 10:23

1 Answers1

3

Both solutions expressed in the comments are good.

If your array size wont change, you can continue with your array. But before adding your number inside the first element of your array, you need to initialize it with at least one element

int[] numbers = new int[1];
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
numbers[0] = number

If your gonna change the size of the array during execution, I strongly recommend you to stop using arrays and to use List.

List<Integer> numbers = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
numbers.add(number);
vincrichaud
  • 2,218
  • 17
  • 34
  • what is the difference between a list and an arraylist? – Hagelsnow Nov 17 '21 at 10:57
  • 2
    @Hagelsnow `List` is the interface while `ArrayList` is the actual implementation of that interface. See: [Type List vs type ArrayList in Java](https://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java) and [What does it mean to "program to an interface"?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – OH GOD SPIDERS Nov 17 '21 at 11:09