Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array for series of integers in Java?

Tags:

java

arrays

list

I've been up for a few hours trying to find a solution.

My program asks the user to enter a list of integers (example: 5 2 5 6 6 1). Then I would like to create an array and store each integer into its respective array index, consecutively.

Here is the part of my program i'm having trouble with (this program was meant to perform calculations via a method later on, but I didn't include that):

import java.util.Scanner;
public class Assignment627 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    int x = 0;
    int[] list1Array = new int[1];

    System.out.println("Enter list1: ");
    while (input.hasNext()){
        list1Array[x] = input.nextInt();
        x++;
    }

As you can see, I am instantiating the array "list1Array" but the problem is I don't know how many integers the user would enter! If only there were a way of knowing how many integers have been input... Any help would be greatly appreciated! Thanks, Sebastian

like image 812
seba1685 Avatar asked Mar 29 '26 21:03

seba1685


1 Answers

import java.util.Scanner;
public class Assignment627 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        //int[] list1Array = new int[1];
        List<Integer> list1Array = new ArrayList<>();

        System.out.println("Enter list1: ");
        while (input.hasNext()){
            list1Array.add(input.nextInt());
        }   
    }

}

An ArrayList, is like an array that does not have a predefined size and it dynamically changes its size; exactly what you are looking for. You can get its size by list1Array.size();

If you insist on having the final result as an array, then you can later call the toArray() method of ArrayList. This post will be helpful.

like image 88
vefthym Avatar answered Mar 31 '26 11:03

vefthym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!