Re: Help with learning arrays

From: Andrew Thompson (SeeMySites_at_www.invalid)
Date: 11/28/04


Date: Sun, 28 Nov 2004 17:38:15 GMT

On Sun, 28 Nov 2004 17:12:01 GMT, Jo Campbell wrote:

> I would like to create an array where I can generate a random number and
> have it "move" to that particular spot on the array ..

Why?

> .. and then give me a JOptionPane ..

It is probably too early to be rushing into GUI development,
stick with the command line for the moment.
<http://www.physci.org/codes/javafaq.jsp#appfirst>

>..that tells me where it went. I just can't
> seem to make the leap to figure out what to do next.

Further comments in the code.

<sscce>
import java.util.Random;

/** 'test' is an exceedingly bad name for a class.
Class names should start with EachWordCapital and
be descriptive. I suggest ArrayTest. */
public class test {

  /** Please indent your code uniformly. */
  public static void main (String args[]) {

    int array1[][]=new int [6][6];
    /** It is good practise to wrap even single line
    statements within if/else or loop structures in {}, as
    it makes the flow more clear. */
    for (int i=0; i<6; i++) {
      for (int j=0; j<6; j++) {
        array1[i][j]=0;
      }
    }

    // what is 'r'?
    //int r = 0;

    // you can declare moves in the 'for' statement
    //int moves = 0;

    /** You do not need to create the Random object 100 times,
    in fact, it is bad practise. for two reasons.
    1) Creating objects is a lot more expensive than reusing
    an existing object.
    2) You risk getting numbers that are somewhat less than random,
    since the Random object uses the current time as a 'seed' for
    the random number generator. */
    Random generator = new Random();

    for (int moves = 0; moves<100; moves++) {
      // a better name is index1
      //int num1;

      // but you need two of them..
      int index1, index2;

      // what made you choose '7'? You need a number from 0-5.
      //num1 = generator.nextInt(7);
      index1 = generator.nextInt(5);
      index2 = generator.nextInt(5);

      System.out.println( index1 + "," + index2 );
    }
  }
}
</sscce>

HTH

-- 
Andrew Thompson
http://www.PhySci.org/codes/  Web & IT Help
http://www.PhySci.org/  Open-source software suite
http://www.1point1C.org/  Science & Technology
http://www.LensEscapes.com/  Images that escape the mundane


Relevant Pages