You need to split it up into sections.
First: Get positive number
double i;
double k;
Console.Write("What is your total income : ");
while (!double.TryParse(Console.ReadLine(), out i) || i < 0)
{
if (i < 0)
{
Console.WriteLine("Your income cannot be negative.");
}
else
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
}
Second: Get number of children
Console.Write("How many children do you have: ");
while (!double.TryParse(Console.ReadLine(), out k) || k < 0)
{
if (k < 0)
{
Console.WriteLine("You must enter a positive number.");
}
else
{
Console.WriteLine("You must enter a valid number.");
}
}
Third: Calculate
double totalTax = (i - 10000 - (k * 2000)) * 0.02;
if (totalTax <= 10000)
{
Console.WriteLine("You owe no tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
else
{
Console.WriteLine("You owe a total of $ " + totalTax + " tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
Whenever you get a wrong input, the while loop forces you to stay inside. When you get out, you can be sure the input is correct.
PS: I would use int
for number of children, because it doesn’t make any sense that you would have 2.3 children.
4
solved C# while loop not functioning [closed]