how can I fix this error in c # [closed]

0
static double LeerAños()
   {
        int az;
        Console.WriteLine("Ingrese los años que se le daran de plazo");
        az = int.Parse(Console.ReadLine());
        while(!(az >= 2 && az <= 7))
        {
         Console.WriteLine("ERROR\n Ingrese los años que se le daran de plazo");
         az = int.Parse(Console.ReadLine());
        }
      return az;
    }
    
asked by enrique fuentes 13.05.2017 в 02:51
source

2 answers

2
  

How can I solve this error in c #

Sadly, you have not told us what your mistake is. In the future, it would be nice to include all the relevant details in your question.

Even so, since your program is not complicated, I only see one type of error that can give you problems. This would happen when during data entry, the value is not numeric. In that case, the use of int.Parse is going to launch a NumberFormatException .

To avoid this error, you need to use int.TryParse instead of int.Parse . Instead of launching a NumberFormatException , int.TryParse returns false if the value is not numeric, and true if it is.

Making some small improvements to your code:

  • Replacing int.Parse with int.TryParse
  • Changing the type of the function from double to int
  • Translating condition !(az >= 2 && az <= 7) to az < 2 || az > 7
  • Avoiding unnecessary repetition by moving the parse directly within the while

... your method would look like this:

static int LeerAños()
{
    Console.WriteLine("Ingrese los años que se le daran de plazo");
    int az;

    while (!int.TryParse(Console.ReadLine(), out az) || az < 2 || az > 7)
    {
        Console.WriteLine("ERROR\n Ingrese los años que se le daran de plazo");
    }

    return az;
}
    
answered by 13.05.2017 в 04:36
0

A more optimal way to implement, could be like this:

static int LeerAnios()
    {
        int az;
        do
        {
            Console.WriteLine("Ingrese los años que se le daran de plazo");
            az = int.Parse(Console.ReadLine());
        } while (!(az >= 2 && az <= 7));
        return az;
    }

Greetings, I hope it serves you.

    
answered by 13.05.2017 в 03:06