I am trying to create a class that collects the sum of an integer that is collected from a console window. First, the class asks how many numbers to sum, and then reads that there are a lot of integers from the console.
If the user enters a number with a decimal point, which is unacceptable, 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 information 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();
Console.WriteLine();
}
But now the question that I have comes up, in SumNumbers, he asks the user to specify the value of the number that he / she wants to add using the for loop, which depends on what the user enters into ReadInput.
private void SumNumbers()
{
int index;
int num = 0;
for (index = 1; index <= numOfInput; index++)
{
Console.Write("Please give the value no. " + index + " (whole number):");
num = Input.ReadIntegerConsole2();
sum += num;
}
}
I have a problem in that I want the error message to continue the for loop after sending the message. For example, I want to sum 2 numbers, so first I add 1, and then prints the console: give the value no.2 (integer): but, let's say I then type 1.6, which is not allowed, then the Imprints console: wrong input. Try again. Now I want this to continue with the same question as before: "Please indicate value No. 2 (integer):"
How can I do it? The input class is as follows:
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. " + " (whole number):");
return ReadIntegerConsole2();
}