简体   繁体   中英

How to repeat code line if a while loop if condition is true c#

I need help with an while loop for the following code:

using System;

namespace Sample
{
    class Program
    {
        static int Main(string[] args)
        {
            int num1;
            int num2;
            //This collects the price as input from the user
            Console.Write("Enter Price: ");
            num1 = Convert.ToInt32(Console.ReadLine());
            //This collects the amount paid as input from the user
            Console.Write("Paid: ");
            num2 = Convert.ToInt32(Console.ReadLine());
            decimal price = num2 - num1;
            Console.WriteLine("{0} - {1} = {2}", num2, num1, num2 - num1);
            while (num2 < num1)
            {
                Console.WriteLine("You have paid less than the price");
                Console.WriteLine("\nPlease pay an amount equals to/greater than "+num1);
                num2 = Convert.ToInt32(Console.ReadLine());
            }
            return num2 = Convert.ToInt32(Console.ReadLine());
        }
    }
}

I want the code to display the message AND ask the user again for the input 'Console.Write("Paid: ");' if the amount paid is less than the price. The current code will only display the message but will not prompt user to enter the price again. Can you please help with this

That's because you want the user to pay the price/above the price at once. Take a look at this code:

static void Main(string[] args)
    {
        int price;
        int paid;
        //This collects the price as input from the user
        Console.Write("Enter Price: ");
        price = Convert.ToInt32(Console.ReadLine());
        //This collects the amount paid as input from the user
        Console.Write("Paid: ");
        paid = Convert.ToInt32(Console.ReadLine());
        decimal change = paid - price;
        Console.WriteLine("{0} - {1} = {2}", paid, price, change);
        while (paid < price)
        {
            Console.WriteLine("You have paid less than the price");
            Console.WriteLine("\nPlease pay an amount equals to/greater than " + price);
            paid += Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("You have paid:" +paid);
        }

        Console.WriteLine("You have paid enough, the price was {0} and you paid {1}", price, paid);
    }

I've changed the variable names to make it a bit more clear what's happening. With this code you add the new input to your last input, so eventually will the variable 'paid' be bigger than variable 'price'and thus end the program after the required amount is reached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM