While statements- forgive the noob
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: While statements- forgive the noob

  1. #1
    Join Date
    Sep 2012
    Posts
    1

    While statements- forgive the noob

    I am new to C# and created the following while loop:

    while (months <= 12)
    while (months >= 60)
    {
    Console.Write("Invalid months. Must be >= 12 and <= 60");
    Console.Write("\nEnter the number of months in the lease::");
    months = Convert.ToInt32(Console.ReadLine());
    }

    Is this correct?

  2. #2
    Join Date
    Jul 2012
    Posts
    90

    Re: While statements- forgive the noob

    You need to do a Console.ReadLine before entering the loop (months will be 0 unless you do). And then again inside the loop (like you already are).

    If you don't want to do the Console.ReadLine prior to the while, you can set it to an arbitrary number to get in the loop, then move the Console.ReadLine to the beginning of the loop e.g.

    Code:
    Int32 months = 12;
    while (months >= 12 && months <= 60)
    {
        months = Convert.ToInt32(Console.ReadLine());
        if (months >= 12 && months <= 60) { break; }
        Console.Write("Invalid months. Must be >= 12 and <= 60");
        Console.Write("\nEnter the number of months in the lease::");
    }
    You also need an exit from the loop if the entered value is in the appropriate range. This is what the if statement does.
    Last edited by Arjay; September 22nd, 2012 at 03:18 PM. Reason: Add code tags

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center