[java] assigning values to 8 ints -help-

Started by
12 comments, last by lupine 23 years, 4 months ago
oh I see, you must be familiar with C or some other language like that. I know mainly java but I''m taking C and I was surprised at how strange arrays are in C. So for starters forget all that old stuff. Arrays are objects. Apparently they are implemented differently but from your point of view treat them exactly like all other objects. So if I say a = new int[5] it is like making a class with the following members:

class intArray
{
int 0;
int 1;
int 2;
int 3;
int 4;
} //keeping in mind that you can''t name things 0,1,2,etc..

and instead of writing a.2 you write a[2] ok on to your code

public void gran(int stats[])
{
stats[1]=(int)(1+ Math.random ()*6);
}

ok what you are doing here is getting a reference to an array and returning nothing, but you don''t need to. The first and only line generates a random integer and assigns it to the second variable of stats. The other ones aren''t mentioned in your code so they aren''t altered.

static void myArray(int y[])
{
y = new int[8];//y is allocated 8 ints
//anon: well, not exactly, a new object is made with 8 members
//don''t think of this being low level memory management

for(int i = 0; i < y.length; i++)
{
y = (int)(1 + Math.random() * 6);
}
//does this even compile? It shouldn''t.
//y holds a reference to an object that can hold 8 ints
//y is not the address to y[0] so the only thing that can
//legally be assigned to y is an int[] object, not a primitive int.
//If you want to assign an int to an index you have to assign it to that index.

}

The following should take an array and assign a different random int to each index:

public void assignInts(int[] y)
{
for (int i=0; i{
y=(int)(1 + Math.random()*6);
}
}

not sure if that is what you are asking for.
Advertisement
oh wait let me try that again

public void assignInts(int[] y)
{
for (int i=0; i{
y=(int)(1 + Math.random()*6);
}
}

yes it compiles.
and it runs-i get all zero's-
I can assign variables in
a FOR-loop.
I want a method (or class?)
I can call on from anywhere
and say
"assign every int in this array
a random number(1-6)"
----------------------------------
wait a minute i tried that "public void"
and i got a "cannot call a static/public"
something something


Edited by - lupine on November 22, 2000 8:25:26 PM
"do you like my helmut?"-yoghurt
what??? it is deleting parts of my code, probably yours too. Ok instead of brackets I am going to use B, and I am going to leave the for loop empty, just fill in the standard incrementing system with the i plus plus.

public void assignInts(int[] y)
{
for ()
{
yBiB=(int)(1 + Math.random()*6);
}
}

This topic is closed to new replies.

Advertisement