C
C#3mo ago
zzz

catching exception but skipping an iteration

using System.Security.Cryptography.X509Certificates;

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

int numTotal;
int count = 0;

Console.WriteLine("Welcome to my calculator.");
Console.WriteLine("How many numbers are in your calculation?");
numTotal = int.Parse(Console.ReadLine());
int[] numbers = new int[numTotal];
while (count < numTotal - 1)
{
for (int i = 0; i < numTotal; i++)
{
Console.WriteLine($"Enter number {i + 1}");
try
{
numbers[i] = int.Parse(Console.ReadLine());
count = count + 1;
}
catch (Exception)
{
Console.WriteLine("I said a number lil bro :/");
}
}
}
}
}
}
using System.Security.Cryptography.X509Certificates;

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

int numTotal;
int count = 0;

Console.WriteLine("Welcome to my calculator.");
Console.WriteLine("How many numbers are in your calculation?");
numTotal = int.Parse(Console.ReadLine());
int[] numbers = new int[numTotal];
while (count < numTotal - 1)
{
for (int i = 0; i < numTotal; i++)
{
Console.WriteLine($"Enter number {i + 1}");
try
{
numbers[i] = int.Parse(Console.ReadLine());
count = count + 1;
}
catch (Exception)
{
Console.WriteLine("I said a number lil bro :/");
}
}
}
}
}
}
my code works fine other than when the user doesnt input a number and my exception error prints it skips to the next number instead of asking them to reinput it
No description
4 Replies
Angius
Angius3mo ago
Well, the i in loop still increases, doesn't it Also, probably a better idea to use int.TryParse() rather than catching an exception of int.Parse() In general, exceptions should not be used for control flow
zzz
zzz3mo ago
i just added i = i -1 to the end of my catch is that ok
Angius
Angius3mo ago
Sure Protip: x = x + 1 is just x += 1 is just x++ x = x - 1 is just x -= 1 is just x-- x = x + 2 is just x += 2 and so on
Jimmacle
Jimmacle3mo ago
for the sake of readability i would make the input validation a separate loop that will also help you later when you decide to factor out the input code into another method
Want results from more Discord servers?
Add your server
More Posts