Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

c# Need help trying to put in and run two loops for the same input

I've put in a loop with Try.Parse so that if the user enters a decimal number, the program will ask them to enter another number until they put in a integer and then the program will carry on with the next part. However what i'm struggling with is putting in another loop that makes it so that the user can only enter a number between 1 and 100, and if they don't there should be an error message that loops until they do enter this. Id like them to run at the same time and i have this one, but i want it to also check whether its in the range and i'm not sure how to do that. I'm new to programming so I'm not great at this. Thank you in advance!

        string inputcost;
        string inputmoney;
        int validcost;
        int validmoney;
        int changereq;

        Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
        inputcost = Console.ReadLine();
        bool result = int.TryParse(inputcost, out validcost);

        while (!int.TryParse(inputcost, out validcost))
        {
            if (result == true)
            {
                Console.Write("Valid Value");
            }
            if (result == false)
            {
                Console.Write("Please Enter A Valid Integer Value");
                Console.WriteLine();
                inputcost = Console.ReadLine();
            }
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem here is that the result variable you're looking at is only written once: outside the loop. Consider trying something like the following pseudocode (a do-while loop works exactly the same as a while loop, except it always gets executed once before the condition is checked):

bool validInput;
do
{
    // If you set it true to begin with, you can set it false on any unmet conditions
    // If it doesn't get set false, you've got a valid input and can exit the loop.
    validInput = true;

    Read input from user
    Check if it's a valid integer, if not print message and validInput = false
    Check if it's between 1-100, if not print message and validInput = false;
} while (!validInput);

Then if you want to tackle something more advanced, look at the continue keyword.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...