Home > OS >  method that repeats a loop using user input to determine number of times
method that repeats a loop using user input to determine number of times

Time:11-20

I am having difficulty creating a a for while loop that allows the user to enter a number and that number determines how many times the loop will execute. I need to create this method and have it execute in Main() feeling lost and not sure why my current code isn't working.

 public static int InputValue(int min, int max)
        {
            //determine number of search times
            int val;
            Console.WriteLine("Enter a number between 1-30:");
            val = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < val; i  )

            
            while (val > max || val < min)
            {


                Console.WriteLine("Please enter number within the range...");
                break;
            }
            
            return val;
            
        }

CodePudding user response:

Your while loop looks intended to make sure the input number is in range.

That should happen before your for loop, and the line starting val = ... should be inside that loop. You want to break out of that "input validation" when the condition if being in range is met. I think it reads more naturally to use a do...while loop since the input step will happen at least once.

Finally, your for loop should so something useful.

Here's what all that could look like:

public static int InputValue(int min, int max)
{
    //determine number of search times
    int val;
    Console.WriteLine($"Enter a number between {min}-{max}:");

    do
    {
        val = Convert.ToInt32(Console.ReadLine());
        if (val > max || val < min)
            Console.WriteLine("Please enter number within the range...");
    }
    while (val > max || val < min);


    for (int i = 1; i <= val; i  )
        Console.WriteLine($"Iteration {i} of {val}");


    return val;
}

CodePudding user response:

You have to check if input is valid beforehand.

public static int InputValue(int min, int max) {
    //goes until until input is valid
    while(true) {
        int val = Convert.ToInt32(Console.ReadLine());
        if(val > max || val < min) {
            Console.WriteLine($"Please enter a number between {min} and {max}");
        }
        else {
            /* does whatever once input is valid,,
            I'm not sure what you're trying to do
            with the for loop but do it in here */ 
            return val; 
        }
    }
}
  • Related