Skip to content
Advertisement

Problems using circular array to take inputs and stop/print the last 10 elements once “-1” is entered

I have a Java program that should be doing what the above title describes. Unfortunately, I am now having the issue of having nothing but zeros and a Error message no matter what I input into Scanner.

The code:

JavaScript

The output:

JavaScript

Advertisement

Answer

Like Namandeep_Kaur comment said, your for loop condition is incorrect. You want it to be i < 10 and not i <= 10 because your numArray length is set to 10, however array index is zero-based in Java. So, you will access elements starting with index 0. numArray will have elements at indexes 0-9. Essentially your loop will want to stop when i is equal to 10 because then the condition 10 < 10 is false and you will not try to be accessing the element at numArray[10] which does not exist. Also I have re-factored your program.

JavaScript

I hope this is the result you were looking for in your program. If there’s anything I can clarify further I would be happy to.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement