Skip to content
Advertisement

How do I make a for loop ask a user for the same input again after an Exception?

So to clarify, when the program asks the user for number 1: if the user were to input a letter, I need the program to tell the user that there was an input mismatch, then ask the user for number 1 again. This needs to be achieved using only one single for loop, and there can be no negative numbers that affect the sum or the average. Here’s what I have so far:

JavaScript

Advertisement

Answer

Use a while or a for loop that will increment the loop count ONLY IF a valid input is provided. Your solution increments the loop counter automatically regardless of the validity of the input.

JavaScript

If you choose to use a for loop, remove the counter increment out of the loop declaration

JavaScript

Another point… I don’t think it is necessary to throw an exception if the number is negative. I think it is better to simply execute a continue to avoid incrementing the loop counter. This is the result of this:

JavaScript

As you can see, I entered several negative numbers and the program continued to run without incrementing the loop counter. The complete solution with continue:

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