Hey, Im doin a uni coursework and i need to figure out how to set the
number of elements in an array when its variable.
i know that to set an array with say 7 elements it is
arraytype arrayname[] = new type[7]
but what if i need to get the user to input how many element there will be
in the array.
Any help will be greatly appreciated.
Hal Rosser - 25 Nov 2004 02:20 GMT
> Hey, Im doin a uni coursework and i need to figure out how to set the
> number of elements in an array when its variable.
[quoted text clipped - 3 lines]
> but what if i need to get the user to input how many element there will be
> in the array.
Ask the user with an input dialog - putting it into a String variable (
let's call it 'userInput')
ArrayType arrayName[] = new ArrayType[Integer.parseInt(userInput)]
Uni_Student - 25 Nov 2004 02:41 GMT
thats cool, but when assigning the then input variables to the individual
elements of the array how do i do that? My code so far looks like this:
//Read in amount of numbers to have calculations performed on
System.out.println("Please enter how many numbers you wish to perform
calculations on");
initNumber = EasyIn.getByte();
//Create array
double arrNumbers[] = new double[integer.parselnt(initNumber)];
//Read in range of numbers with loop
for (int x = 0; x < initNumber; x++)
{
System.out.println("Please Enter a Number ");
arrIndex = EasyIn.getByte();
}
The part i have labeled as arrayInded it the part i dont know how to
assign to the elements of the array
Mike B - 25 Nov 2004 04:29 GMT
> thats cool, but when assigning the then input variables to the
> individual elements of the array how do i do that? My code so far
[quoted text clipped - 15 lines]
> The part i have labeled as arrayInded it the part i dont know how to
> assign to the elements of the array
Think about it differently. You are not reading in the index, you are
reading in the value to be stored at that index. The index is the variable
that controls how many times you are going to loop.

Signature
Mike B
Boudewijn Dijkstra - 25 Nov 2004 09:00 GMT
> Hey, Im doin a uni coursework and i need to figure out how to set the
> number of elements in an array when its variable.
>
> i know that to set an array with say 7 elements it is
> arraytype arrayname[] = new type[7]
You have this the wrong way around. The conventional sequence is:
type name = initialization;
which in this case is:
elementType[] arrayName = new elementType[size];
because elementType[] is the (array)type.