Home > OS >  how to print an array with bracket and coma?. I write a code but its have 0 value inside the bracket
how to print an array with bracket and coma?. I write a code but its have 0 value inside the bracket

Time:10-05

System.out.print("Enter size: ");
int size = input.nextInt();

int[] array = new int[size   1];

for (int ctr = 1; ctr < size   1; ctr  ) {
    System.out.print("Enter element "   ctr   ": ");
    array[ctr] = input.nextInt();
}
         
System.out.println( Arrays.toString(array));

how can I make this output:

Enter·size:·10
Enter·element·1:·1
Enter·element·2:·2
Enter·element·3:·3
Enter·element·4:·4
Enter·element·5:·5
Enter·element·6:·6
Enter·element·7:·7
Enter·element·8:·8
Enter·element·9:·9
Enter·element·10:·10
[1,2,3,4,5,6,7,8,9,10]

CodePudding user response:

Your array has 1 more element than needed(the first one, at index 0), which you never assign value to.

Make the array with size = size, not size 1:

int[] array = new int[size];

The iterate from 0 to size and calculate the number of the element dynamically using the index:

for (int index = 0; index < size; index  ) {
    System.out.print("Enter element "   (index   1)   ": ");
    array[index] = input.nextInt();
}

CodePudding user response:

Something important to consider: Java arrays start at at index = 0, not at index = 1

Since you never set the value at index 0, it defaults to 0.

What you need to do:

You don't need to initialize as size 1 here

int[] array = new int[size   1];

This is sufficient

int[] array = new int[size];

In your for loop, instead of

array[ctr] = input.nextInt();

Change it to

array[ctr-1] = input.nextInt();
  • Related