Home > front end >  How to add a value to an array
How to add a value to an array

Time:11-18

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();

CodePudding user response:

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);
  • Related