user3131148
user3131148

Reputation: 353

How to create an empty array?

Am new and I've searched the web and found it a bit frustrating, all I got was that in java array's can't be re-sized. I just want to figure out How do I create an empty array where I then prompt the user to enter numbers to fill the array? I don't want to define the capacity of the area like int[] myArray = new int[5]; I want to define an empty array for which a user defines the capacity, example- they enter number after number and then enter the word end to end the program, then all the numbers they entered would be added to the empty array and the amount of numbers would be the capacity of the array.

Upvotes: 9

Views: 136452

Answers (6)

Jerry Chong
Jerry Chong

Reputation: 9220

Since you are using for integer, can try using ArrayList with following example:

ArrayList<Integer> integerListArray = new ArrayList<Integer>();

Upvotes: 0

Rogue
Rogue

Reputation: 11483

How about:

Scanner scan = new Scanner(System.in);
System.out.print("Enter the array size: ");
int size = scan.nextInt();
int[] yourArray = new int[size];
//can even initialize it
Arrays.fill(yourArray, -1);

Upvotes: 6

iDJ2012i
iDJ2012i

Reputation: 21

Take n from the user input and:

int a [] = new int [n];

Upvotes: 0

user3533325
user3533325

Reputation: 11

    import java.util.Scanner;


public class Ex {
public static void main(String args[]){
    System.out.println("Enter array size value");
    Scanner scanner = new Scanner(System.in);
    int size = scanner.nextInt();
    int[] myArray = new int[size];
    System.out.println("Enter array values");
    for(int i=0;i<myArray.length;i++){
        myArray[i]=scanner.nextInt();
    }
    System.out.println("Print array values");
    for(int i=0;i<myArray.length;i++){
        System.out.println("myArray"+"["+i+"]"+"="+myArray[i]);
    }
}
}

Upvotes: 1

JNevens
JNevens

Reputation: 11982

You cannot make an empty array and then let it grow dynamically whenever the user enters a number in the command line. You should read the numbers and put them in an ArrayList instead. An ArrayList does not require a initial size and does grow dynamically. Something like this:

public void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    BufferedReader console = 
            new BufferedReader(new InputStreamReader(System.in));
    while(true) {
        String word = console.readLine();
        if (word.equalsIgnoreCase("end") {
            break;
        } else {
            numbers.add(Integer.parseInt(word);
        }
    }

Ofcourse you won't use while(true)and you won't put this in main, but it's just for the sake of the example

Upvotes: 10

zaPlayer
zaPlayer

Reputation: 862

try ArrayList, it's a dynamic array http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Upvotes: 1

Related Questions