1

I am new to java,I have created array which accepts 8 values. It's working fine,also accepting values but it's not displaying correct output on console,please help me what the problem can be ??

Here's my code,

import java.util.*;


public class array2

{
    public static void main(String []args)

    {


        Scanner scan=new Scanner(System.in);    
    int[] nums=new int[8];  

        for(int count=0;count<8;count++)

        {

            nums[count]=scan.nextInt();     

        }


        System.out.println(nums);


    }



}
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
sam
  • 29
  • 5

6 Answers6

3

Use System.out.println(Arrays.toString(nums)); (import java.util.Arrays to do this)

If you just say System.out.println(nums);, it will only print the object reference to the array and not the actual array elements. This is because array objects do not override the toString() method, so they get printed using the default toString() method from Object class, which just prints the [class name]@[hashcode] of the object instance.

Hari Menon
  • 33,649
  • 14
  • 85
  • 108
1

This is because you are printing the array object instead of elements

Use this

for(int i : nums){
   System.out.println(i);
}
  • The [ symbol in the output indicates that the object being printed is an array.
  • Alternatively, you can do System.out.println(Arrays.toString(nums));. This gives String representation of the array.
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
1

Printing an array like that is not possible in Java, you probably got something like "[I"... Try looping:

for (int n=0; n<nums.length; ++n)
  System.out.println(nums[n]);
HammerNL
  • 1,689
  • 18
  • 22
0

Display array in a loop:

for(int count=0; count<8; count++)
{
   System.out.println(nums[count])
}

You are printing array reference, not their elements.

Pawel
  • 1,457
  • 1
  • 11
  • 22
0

You need to use Arrays.toString(int[]), to create string that will contain the expected from. Currently you are printing string representation of array itself.

0

nums[count]=scan.nextInt() will only print the memory location of the array and not the array contents. To print the array contents you need to loop as you did when you insert them. I would try:

for(int count=0;count<8;count++){

    System.out.println(nums[count]);
 }

Hope that helps

Cuta
  • 71
  • 2
  • 9