2012-01-17 3 views
1

Я хотел бы иметь возможность в калькуляторе цены со скидкой, который я написал для удовольствия, чтобы запустить программу, и задавался вопросом, как я оптимально буду заниматься этим. Я хотел бы, чтобы он сказал что-то похожее: «Не хотите ли вы ввести другую цену?» и если пользователь говорит «да» или «у» или «нет» и т. д., перезапустите программу или выйдите. Я должен, вероятно, использовать цикл if правильно? Может кто-нибудь, пожалуйста, покажите мне, как его реализовать? Или указать мне в правильном направлении? Мне также кажется, что я должен переписать программу, чтобы иметь методы, но я не знаком с C#.Как я могу реализовать простое текстовое меню в консольном приложении?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Figure_the_Discount 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     string price, discount; 
     decimal discountedPrice, savedAmount; 

     //Receiving the price as input 
     Console.WriteLine("Please enter the price of the item."); 
     price = Console.ReadLine(); 
     decimal numPrice = decimal.Parse(price); 

     //Receiving the discount as input 
     Console.WriteLine("Please enter the discount that you wish to apply"); 
     discount = Console.ReadLine(); 
     //Receiving discount from input, divide by 100 to convert to percentile 
     decimal numDiscount = decimal.Parse(discount)/100; 

     //Calculate the discounted price with price - (price * discount) 
     discountedPrice = numPrice - (numPrice * numDiscount); 
     //Calculate the amount of money they saved 
     savedAmount = numPrice - discountedPrice; 
     Console.WriteLine("The discounted price of this item is: ${0}\nYou saved: ${1}", discountedPrice, savedAmount); 
     Console.ReadLine(); 

    } 
} 
} 
+0

Это выглядит хорошо для меня. На самом деле кода недостаточно, чтобы использовать методы, если вы не хотите добавить что-то еще? –

+0

Вам следует попытаться сделать то, что вы сказали. – neeKo

+0

Похоже, что ответы других людей решат вашу проблему. Просто подумал, что я дам вам знать, что вы должны использовать decimal.TryParse вместо decimal.Parse. Таким образом ваша программа не взорвется на вас, если введен неверный десятичный знак. –

ответ

0

следующий цикл будет циклически до тех пор, пока пользователь указывает y или yes (не чувствительно к регистру) в конце программы.

static void Main(string[] args) 
{ 
    string price, discount; 
    decimal discountedPrice, savedAmount; 
    bool startAgain = true; 
    string line; 

    // Loop again every time the startAgain flag is true. 
    while (startAgain) 
    { 
     //Receiving the price as input 
     Console.WriteLine("Please enter the price of the item."); 
     price = Console.ReadLine(); 
     decimal numPrice = decimal.Parse(price); 

     //Receiving the discount as input 
     Console.WriteLine("Please enter the discount that you wish to apply"); 
     discount = Console.ReadLine(); 
     //Receiving discount from input, divide by 100 to convert to percentile 
     decimal numDiscount = decimal.Parse(discount)/100; 

     //Calculate the discounted price with price - (price * discount) 
     discountedPrice = numPrice - (numPrice * numDiscount); 
     //Calculate the amount of money they saved 
     savedAmount = numPrice - discountedPrice; 
     Console.WriteLine("The discounted price of this item is: ${0}\nYou saved: ${1}", discountedPrice, savedAmount); 
     Console.ReadLine(); 

     // Ask if the user wants to submit another price. 
     Console.WriteLine("Would you like to enter another price?"); 
     // Record the spaceless, lower-case answer. 
     line = Console.ReadLine().ToLowerCase().Trim(); 
     // Set the startAgain flag to true only if the line was "y" or "yes". 
     startAgain = line == "y" || line == "yes"; 
    } 
} 
0

Вы можете сделать это:

static void Main(string[] args) 
{ 
    string resp = ""; 
    string price, discount; 
    decimal discountedPrice, savedAmount; 
    do { 
     .... // your previous code here 
     .... 
     Console.WriteLine("The discounted price of this item is: ${0}\nYou saved: ${1}", discountedPrice, savedAmount); 
     Console.WriteLine("Another item?"); 
     string resp = Console.ReadLine().ToLower(); 
    } 
    while (resp == "y" || resp == "yes"); 
    Console.ReadLine(); 
} 
0

Just сек грубый образец

string input = null; 
do { 


    //your code 

    Console.WriteLine("Would you like to insert another price?"); 
    input = Console.ReadLine(); 
    if(input.ToLower() != "y" || //if responce to the question is not 'y' or 'yes', break the loop 
     input.ToLower() != "yes") 
    break; 

}while(true); 

EDIT

Эта программа вставляет цену до пользователь подтверждает, что он хочет вставьте новую цену, иначе просто выйдите.

Смежные вопросы