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();
2
  • 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;? Commented Nov 17, 2021 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<Integer> numbers = new ArrayList<>(); Commented Nov 17, 2021 at 10:23

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

what is the difference between a list and an arraylist?
@Hagelsnow List is the interface while ArrayList is the actual implementation of that interface. See: Type List vs type ArrayList in Java and What does it mean to "program to an interface"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.