-1

i have an simple console application and i want that use be able of only enter numbers. here's the code

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
        int n, sum;
        sum = 5000;
        Console.WriteLine("enter number of conversations");
        n = int.Parse(Console.ReadLine());
        if (n <= 100)
        {
            sum = sum + n * 5;
        }
        else
        {
            sum += (100 * 5) + (n - 100) * 7;
        }
        Console.WriteLine(sum);
        Console.ReadKey();
        }
    }
}
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
Sky Team
  • 9
  • 1
  • 1
  • 1

3 Answers3

3

This should do the trick.

Console.Write("enter number of conversations ");
int n;

while(!int.TryParse(Console.ReadLine(), out n)
{
     Console.Clear();
     Console.WriteLine("You entered an invalid number");
     Console.Write("enter number of conversations ");
}

if(n <= 100)
  //continue here
Tom Biddulph
  • 514
  • 6
  • 16
2

Bet option for you in this case is int.TryParse instead for int.Parse() which helps you to determine invalid inputs. You can implement the following logic to make it works;

Console.WriteLine("enter number of conversations");
if(int.TryParse(Console.ReadLine(), out n)
{
    if (n <= 100)
    {
        sum = sum + n * 5;
    }
    else
    {
        sum += (100 * 5) + (n - 100) * 7;
    }
    Console.WriteLine(sum);
}
else
{
   Console.WriteLine("Invalid input , Enter only number");
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
1

You should use the "TryParse" methode instead of "Parse" and use a "do{...}while" loop so you don't have to repeat ugly code.

Note I've added a string variable to handle the user input. This code will ask for the number of conversion again and again until a valid number is entered. Then it'll execute the rest of your code.

class Program
{
    static void Main(string[] args)
    {
        int n, sum;
        string input;
        sum = 5000;

        do
        {
            Console.WriteLine("enter number of conversations");
            input = Console.ReadLine();
        } while (int.TryParse(input, out n) == false);

        if (n <= 100)
        {
            sum = sum + n * 5;
        }
        else
        {
            sum += (100 * 5) + (n - 100) * 7;
        }
        Console.WriteLine(sum);
        Console.ReadKey();
    }
}
TaiT's
  • 3,138
  • 3
  • 15
  • 26