Miroslav Trifonov
Miroslav Trifonov

Reputation: 23

Enter array without knowing its size

Is there a way to make an array in Java, without defining or asking for its length first?

A.k.a the user enters some numbers as arguments, and the program creates an array with that many arguments.

Upvotes: 1

Views: 66157

Answers (6)

Aakash
Aakash

Reputation: 87

You can use String to take input and then convert/use it using Integer.parseInt().

Using this you don't have to allocate an oversized array.

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        
        Scanner s = new Scanner(System.in);
        String val = s.nextLine();
        String[] arr = val.split("\\s+");
        for(int i=0; i<arr.length; i++){
            System.out.print(" " + Integer.parseInt(arr[i]) );
        }
    }
}

Upvotes: 0

PrathiSaiHarika
PrathiSaiHarika

Reputation: 101

Yes, I have read both the arr element and the corresponding space followed by it.

And when encountered newline(\n), stopped reading the input further.

int main()
{
char temp;
int arr[100];
int j = 0;

while (1)
{
    scanf("%d%c", &arr[j++], &temp);
    if (temp == '\n')
        break;
}
printf("%d", j);
}

So. here j is specifying the array size. Hope, I could answer your question.

Have a good day.

Upvotes: 0

user3437460
user3437460

Reputation: 17454

Is there a way to make an array in java, without defining or asking for it's length first ?

Yes, it is possible in Java. This is not possible in C++ though. C++ requires the size of the array to be determined at compile time.

In Java you can create new arrays at run time.

int[] array; //Create a reference of int array (no arrays created yet)

//Prompt for size..
Scanner scn = new Scanner(System.in);
System.out.println("Enter size of array;")
int size = scn.nextInt();

array = new int[size]; //this is allowed in Java

Some additional information:

Take note that arrays are fixed size. Once the size is determined (even at run time) you cannot change it anymore. However there is a work-around solution if you want to "expand" the array size.

//continuing from above coding example..
array = new int[newSize];

Doing this will point array to a new array. So if you want to keep the values of the old array, you have to manually copy the old array elements to the new array. However, this is not efficient.

An efficient way to grow and shrink your array size is to use List or ArrayList. But to answer your question alone on arrays. Yes, you can create it at run time and you can also point your array reference to another array at run time also.

Upvotes: 1

Mike Nakis
Mike Nakis

Reputation: 61969

You need to use an ArrayList for this.

EDIT:

Miroslav is most probably a student trying to complete an assignment. Usually in these assignments you are asked to read values from standard input and do something with them. In this case, store them in an array. So, at the time he has a value to store in the array, he does not know yet how many values are coming. So, ArrayList is the way to go.

Upvotes: 1

Vitalii Bandura
Vitalii Bandura

Reputation: 11

ArrayList is probably the best structure in this situation when you only need to add elements. If you want to add/delete elements from middle of Collection use LinkedList instead.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499830

Is there a way to make an array in java, without defining or asking for it's length first ? A.k.a the user enters some numbers as arguments, and the program creates an array with that many arguments.

It's unclear exactly what situation you're in. If you know the array length at execution time but not at compile time, that's fine:

public class Test {
    public static void main(String[] args) {
        int length = Integer.parseInt(args[0]);
        String[] array = new String[length];
        System.out.println("Created an array of length: " + array.length);
    }
}

You can run that as:

java Test 5

and it will create an array of length 5.

If you really don't know the length of the array before you need to create it - for example, if you're going to ask the user for elements, and then get them to enter some special value when they're done, then you would probably want to use a List of some kind, such as ArrayList.

For example:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter numbers, with 0 to end");
        List<Integer> list = new ArrayList<>();
        while (true) {
            int input = scanner.nextInt();
            if (input == 0) {
                break;
            }
            list.add(input);
        }
        System.out.println("You entered: " + list);
    }    
}

You can then convert that List into an array if you really need to, but ideally you can just keep using it as a List.

Upvotes: 3

Related Questions