Hi all. I am learning Java, and having a problem with a sentinel loop to fill an array.
I want the loop to terminate when -1 is added, OR when the array is filled.
int i = 0;
int counter = 0;
int[] array = new int[40];
System.out.print("Enter values to be added to the array." +
" Enter -1 to stop adding values. ");
array[i] = keyboard.nextInt();
while(array[i] != -1 && counter < array.length)
{
i++;
counter++;
System.out.print("Enter values to be added to the array." +
" Enter -1 to stop adding values. ");
array[i] = keyboard.nextInt();
}
return array;
I'm really having two problems:
(1) It is using -1 as a value in my array, thus impacting methods I use later, and
(2) If I am to add numbers not valued as -1, it goes out of bounds.
Any help to point me in the right direction would be greatly appreciated.