Christopher Baldwin
Christopher Baldwin

Reputation: 347

Array not printing the value of index, printing address instead

Hookay, so, I'm having trouble understanding this problem. To be completely honest, arrays infuriate and confuse me. ...That's part of learning though right?

So here's my problem

Netbeans is outputting this -_- wtf netbeans

Here be the code

//////Problem 4////////
   System.out.println("Please Enter the Size of your array");
   int arraysize = in.nextInt();
   //initalize array
   int [][] aOne = new int[arraysize][arraysize];

   // load array 1  
  for (int i = 0; i< aOne.length; i++){
      for(int x = 0; x <aOne[i].length;x++){
          aOne[i][x] = (int)(Math.random()* 15);}}
  //print aOne
  for (int i = 0; i< aOne.length; i++){
      for (int x = 0; x<aOne.length; x++){
          System.out.print(aOne[i]+" "+aOne[x]);
      }
      System.out.println();
  }

What is going on?

edit: I understand it's giving me the memory locations... why isn't it printing out the numbers? Sorry. The title is the question in my book, I'm having trouble with arrays in general

Upvotes: 0

Views: 222

Answers (2)

Mengjun
Mengjun

Reputation: 3197

If you want to print int[] array.

Use aOne[i][x] to print the specified element in int[] array.

In addition, for the second for-loop for printing int[] array, you'd better using x < aOne[i].length instaed of x < aOne.length, since it will cause issue when the number of rows and the numbers of columns in int[] array are different.

Make some some with this,

from

//print aOne
for (int i = 0; i< aOne.length; i++){
  for (int x = 0; x<aOne.length; x++){
      System.out.print(aOne[i]+" "+aOne[x]);
  }
  System.out.println();
}

to

      //print aOne
      for (int i = 0; i< aOne.length; i++){
          for (int x = 0; x<aOne[i].length; x++){
              System.out.print(aOne[i][x]+" ");
          }
          System.out.println();
      }

One run result in console is as follows:

5 0 10 
1 11 8 
7 7 5 

Upvotes: 0

kai
kai

Reputation: 6887

Change the line:

System.out.print(aOne[i]+" "+aOne[x]);

to

System.out.print(aOne[i][x]+" ");

then you will get the numbers. Otherwise you get the memorie adress of the row [i] and [x] of your 2D array.

Upvotes: 2

Related Questions