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.
By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.
Technically you can't make an array empty. An array will have a fixed size that you can not change. If you want to reset the values in the array, either copy from another array with default values, or loop over the array and reset each value.
In python, we don't have built-in support for the array, but python lists can be used. Create a list [0] and multiply it by number and then we will get an empty array.
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
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);
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]);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With