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.
6 Answers
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
Comments
try ArrayList, it's a dynamic array http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
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]);
}
}
}
myArray = new int[someVarSetEarlier]if you want to get the size in advance or use aListif you want the length of the collection to be changed dynamically.ArrayList<Integer>instead