Hey guys.. I am having a small problem with a program I wrote, the problem is that I have an array that stores a user input and it should be numeric only when the user inputs an invalid input like let's say J the program will notifiy them that they have entered an invalid input that is done through a try catch block and that closes the program after that and never ask them again.. Which I want it to ask them again.. Is there anyway I can loop back after the catch work?

Here is the code I wrote

double[] arraySize = new double[testInput]; // an intitlized array inside the statement to for simplicty.. It is used to access the memory address and stores the user input.


                    if (testInput >= MIN && testInput < MAX) // Limiting the input for each test
                    {
                        for (int counter = 0; counter < arraySize.Length; counter++) // counting on the index length which is the array size
                        {


                            Console.WriteLine("Enter number " + counter + ":"); // allowing the user to input for the test 

                            input = double.Parse(Console.ReadLine()); // storing the user input 

                            if (input >= MIN_TEST && input <= MAX_TEST)
                            {
                                arraySize[counter] = input;
                            }

                            else
                            {
                                Console.WriteLine("\nInvalid Input..");
                                counter--;
                                continue;
                            }

                            temp += arraySize[counter]; // adding the info to the array size

                        }

Of course there is more of the code but this is where I am stuck right now and I don't think the other lines affect it.

Thank you

Recommended Answers

All 7 Replies

Now I see why you said my suggestion didn't work :)

You're not actually using try/catch. When you reach line 12, your Double.Parse statement will throw an exception.

This will either go to the innermost try/catch that contains the statement (and is looking for that kind of exception) or crash your application.

Use this instead;

try
{
    input = Double.Parse(Console.ReadLine());
}
catch
{
    Console.WriteLine("Invalid Input! Please enter a number");
    counter--;
    continue;
}

What was happening before, is that your program was throwing an exception and reaching the try catch outside the loop.

commented: No it's just stopping the process, and now I discovered that the main loop in my program is doing a weird thing.. It is asking for the input again if it fails but once it reaches the second part of the loop is won't go back to prompt the user it just jump +0

Here is the whole program.. To make things look more clear, It is really strange how it passes the else and the try catch...

namespace ActualLab1
{
    class Program
    {
        static void Main(string[] args)
        {

            double input; // the user input for each test
            double average=0; // the average for each test
            double majAverage; // the major average of all experiments
            double temp = 0; // a temproray input that stores the user input to an array
            const int MAX = 6;
            const int MIN = 2;
            int testInput=0;
            const int MIN_TEST = -1;
            const int MAX_TEST =  1;
            bool test = false;

            try
            {

                for (int majCounter = 1; majCounter < 5; majCounter++) // since we have 4 experiments the following block will loop 4 times before it outputs the final average.
                {
                    do
                    {
                        try
                        {
                            Console.WriteLine("Enter the number of tests for experiment " + majCounter + ":");

                            testInput = int.Parse(Console.ReadLine());
                        }

                        catch
                        {
                            Console.WriteLine("invalid Input...");
                            majCounter--;
                            continue;
                        }
                    }
                    while(test == true);

                    double[] arraySize = new double[testInput]; // an intitlized array inside the statement to for simplicty.. It is used to access the memory address and stores the user input.


                    if (testInput >= MIN && testInput < MAX) // Limiting the input for each test
                    {
                        for (int counter = 0; counter < arraySize.Length; counter++) // counting on the index length which is the array size
                        {


                            Console.WriteLine("Enter number " + counter + ":"); // allowing the user to input for the test 

                            input = double.Parse(Console.ReadLine()); // storing the user input 

                            if (input >= MIN_TEST && input <= MAX_TEST)
                            {
                                arraySize[counter] = input;
                            }

                            else
                            {
                                Console.WriteLine("\nInvalid Input..");
                                counter--;
                                continue;
                            }

                            temp += arraySize[counter]; // adding the info to the array size

                        }

                        average = temp / arraySize.Length; // getting the single average of a test
                        Console.WriteLine("Average:" + average + "\nThe sum of the experiments was: " + temp); // summing the total results of a test ( for analyzing )
                    }


                    else
                    {
                        Console.WriteLine("\nYour input is not valid.. Please try again"); // if the user input an invalid input they will be prompted
                       // majCounter--;
                    }


                }


                majAverage =+ average / 4; // the final average.

                Console.WriteLine("\nThe final average is: " + majAverage);
                Console.WriteLine("\n\nPress Enter key to ...");
                Console.ReadLine();

            }


            catch
            {
                Console.WriteLine("\nPlease try again.");

                Console.ReadLine();

            }
        }
    }
}

Can you paste the full listing as you have it now?

I just did.. This is the whole program. I really tried to make it work with tryparse but it didn't seem to work at all.

Nevermind I fixed it.. I commented out the most important line.. which is counter-- and majCounter--
and I removed the big Try Catch.

Thank you everyone!

Ok, I think you need to break it down into more manageable chunks.

You have this giant for loop that controls everything in the method, it makes it hard to see what's going on.

So the first thing you need to do is ascertain what chunks of the program there are and can any of it be re-used.

The code to grab a number from the user is easily re-usable :)

public int GetNumberOfTests(int experimentIndex, int min, int max)
{
    do
    {
        Console.Write("Please enter number of tests for experiment #{0} ", experimentIndex + 1);
        try
        {
            int userNumber = int.Parse(Console.ReadLine());
            if(userNumber < min || userNumber > max)
                Console.WriteLine("The number you gave was outside the bounds! Min: {0}, Max: {1}", min, max);
            else
                return userNumber;
        }
        catch
        {
            Console.WriteLine("You didn't enter a number!");
        }
    }while(true);
}

So now we have a method to grab user input, there is a way to have a single method for all user input, but may be more complicated than you're willing to deal with. You'd call it from your main thread like this...

for(int currentIndex = 0; currentIndex < numberOfRuns; currentIndex++)
{
    int numberOfTests = GetNumberOfTests(currentIndex, minTests, maxTests);

    double[] testValues = GetTestValues(numberOfTests);
}

Notice how I have a second method call named GetTestValues. Into this method we pass how many tests there were and we're expecting an array of double back...

public double[] GetTestValues(int numberOfTests)
{
    double[] testValues = new double[numberOfTests];

    for(int currentTest = 0; currentTest < numberOfTests; currentTest++)
    {
        testValues[currentTest] = GetTestValueInput(currentTest, min, max);
    }

    return testValues;
}

public int GetTestValueInput(int currentTest, int maxValue, int minValue)
{
    do
    {
        Console.Write("Enter value for test {0}", currentTest + 1);
        try
        {
            int testValue = int.Parse(Console.ReadLine());
            if(testValue < minValue || testValue > maxValue)
                Console.WriteLine("Value entered was outside bounds. Min: {0}, Max: {1}", minValue, maxValue);
            else
                return testValue;
        }
        catch
        {
            Console.WriteLine("You must enter a valid number!");
        }
    }while(true);
}

And that should be it :)

The rest of it should be straightforward for you.

Remember: Reusability = Good, Readability = Good, Maintainability = Good.
Writing code in small chunks by what it does is good practice and as you can see makes the main loop a whole lot more readable :)

commented: I totally agree with you.. I would use method s if he allows us to do so, I love using methods, they make the coding much easier but that's all what I got.. I fixed it and handed it in, it works just fine but I am not happy of the way I coded it. +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.