Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a value to an array

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading