-1

Why is this happening, why isnt it giving me *ThisIsWhatItShouldBe

Code

class ArreyTable{ 
    public static void main(String OKM[]){              
        System.out.println("Index\tValue");         
        int px[] = {144,240,360,480,720};               
        for(int counter=0; counter<px.length; counter++){           
            System.out.println(counter + "\t" + px);        
        }           
    }
}

cmd Result

Index     Value
 0         [I@7852e922 
1          [I@7852e922 
2          [I@7852e922 
3          [I@7852e922 
4          [I@7852e922

ThisIsWhatItShouldBe

Index   Value
0          144
1          240
2          360
3          480
4          720
Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53

4 Answers4

3

You're printing the entire array instead of the relevant element of it, which you can access by the [] operator:

for(int counter=0; counter<px.length; counter++){
    System.out.println(counter + "\t" + px[counter]);
    // Here ------------------------------^
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

In the code block

for(int counter=0; counter<px.length; counter++){           
    System.out.println(counter + "\t" + px);        
}           

You are each time converting the array px to a string, which is [I@7852e922 for internal JVM reasons.

You have to indicate the index on the array:

for(int counter=0; counter<px.length; counter++){           
    System.out.println(counter + "\t" + px[counter]);        
}           

That will give the desired result.

Additionally you could replace the println with a printf:

for(int counter=0; counter<px.length; counter++){           
    System.out.printf("%2d: %3d%n", counter, px[counter]);        
}           
M. le Rutte
  • 3,525
  • 3
  • 18
  • 31
0

just change this line : System.out.println(counter + "\t" + px[counter]);

So it will know what value to return ;)

Kiri
  • 13
  • 1
0

You were originally printing the entire px array object. What was being printed was the output of the toString() function of the array object.

Object.toString() method returns a string, composed of the name of the class, an @ symbol and the hashcode of the object in hexadecimal.

when you use px[counter], it references to the element value at that index.

Correct solution would be:

for(int counter=0; counter<px.length; counter++){           
        System.out.println(counter + "\t" + px[counter]);        
    }