Quantcast
Channel: Continue loop between classes after wrong input - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Continue loop between classes after wrong input

$
0
0

I'm trying to make a class that is going to sum a number of whole numbers that is collected from the console window. The class first asks for how many numbers to sum and then reads that many integers from the console.

If the user enters a number with a decimal, which isn't allowed, I have another class called Input.cs that sends back a message that asks them to try again. the class has 4 methods, WriteProgamInfo, ReadInput, SumNumbers and ShowResults. WriteProgamInfo just prints some info with Console.WriteLine, ReadInput asks how many numbers the user wants to add,

private void ReadInput()
{
    Console.Write("Number of values to sum? ");
    numOfInput = Input.ReadIntegerConsole(); //This here is from the Input class that sends an error message if a decimal is being used. This works fine.
    Console.WriteLine();
}

But now comes the issue that I have, in SumNumbers it asks the user to give the value of the number that he/she wants to add using a for loop that is dependant on what the user inputs in ReadInput.

// asks for which numbers to be added, based on how many times
// is given by user in ReadInput
private void SumNumbers()
{
    int index;
    int num = 0;
    for (index = 1; index <= numOfInput; index++) // Loop that asks the quesion d
    {
        Console.Write("Please give the value no. " + index + " (whole number):");
        //This here is from the Input class that sends an error message if a decimal
        //is being used. This is where I have a problem. 
        num = Input.ReadIntegerConsole2();
        sum += num;
    }
}

The problem that I have is that I want the error message to continue the for loop after having sent the message. For instance, I want to sum 2 numbers, so I first add 1, then the console prints: Please give the value no.2 (whole number): but, let's say I then type 1.6 which isn't allowed, the console then prints: Wrong input. Please try again: , Now this is where I want it to continue with the same question as before: "Please give the value no.2 (whole number):"

How do I do this? The input class looks like this:

public static int ReadIntegerConsole2()
{
    int input;
    if (int.TryParse(Console.ReadLine(), out input))
        return input;
    else
        Console.WriteLine("Wrong input. Please try again: ");
    Console.Write("Please give the value no. " + /*index from SumNumbers + */" (whole number):");
    return ReadIntegerConsole2();
}

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images