2017-01-22 6 views
0

Я написал довольно простую программу, которая отображает меню вариантов и выполняет вычисления на основе ввода пользователя. Я хотел бы заставить программу вести себя так, чтобы она запрашивала у пользователя, хотят ли они вернуться к меню или выйти из программы. Я думаю, что это может потребовать какой-то цикл, но я не уверен, как его реализовать.Как разрешить пользователю выбирать, продолжить ли программу или выйти из нее (C#)

Вот мой код

using System; 

namespace WarmUpCalculations 

{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      Console.Clear(); 
      Console.WriteLine("Welcome to the Chemistry Formula Calculator!\n\n\n"); 

      Console.WriteLine("Press 1 for the Density Calculator"); 
      Console.WriteLine("Press 2 for the Moles Calculator"); 
      Console.WriteLine("Press 3 for the Energy of a Wave Calculator"); 
      Console.WriteLine("Press 4 for the Ideal Gas Law Calculator\n\n"); 
      Console.WriteLine("Please enter a Number from the Options above"); 
      string choice = Console.ReadLine(); 

      switch (choice) 
      { 
       case "1": 
        DensityCalculator(); 
        break; 
       case "2": 
        MolesCalculator(); 
        break; 
       case "3": 
        EnergyOfWaveCalculator(); 
        break; 
       case "4": 
        IdealGasLawCalculator(); 
        break; 
      } 
     } 

     static void DensityCalculator() 
     { 
      Console.Clear(); 
      Console.WriteLine("Density Calaculator\n\n"); 
      Console.WriteLine("Will this be for Grams or Kilograms?"); 
      Console.WriteLine("Type 'g' for Grams or 'kg' for Kilograms"); 
      string unitMass = Console.ReadLine(); 

      Console.WriteLine("Please Enter Your Mass"); 
      Decimal Mass = Convert.ToDecimal(Console.ReadLine()); 
      Console.WriteLine("Enter units for Volume"); 
      string unitVolume = Console.ReadLine(); 
      Console.WriteLine("Please Enter Your Volume"); 
      Decimal Volume = Convert.ToDecimal(Console.ReadLine()); 
      Decimal Density = Mass/Volume; 
      Math.Round(Density, 4); 
      Console.Clear(); 
      Console.WriteLine("Moles Calaculator\n\n"); 
      Console.Write("Your Density is "); 
      Console.Write(Density); 
      Console.Write(unitMass); 
      Console.Write("/"); 
      Console.WriteLine(unitVolume); 
      Console.Write(" \n\n"); 

     } 

     static void MolesCalculator() 
     { 
      Console.Clear(); 
      Console.WriteLine("Moles Calaculator\n\n"); 
      Console.WriteLine("Please enter mass of sample"); 
      Decimal Mass = Convert.ToDecimal(Console.ReadLine()); 
      Console.WriteLine("Please Enter Your molar mass"); 
      Decimal MolarMass = Convert.ToDecimal(Console.ReadLine()); 
      Decimal Moles = Mass/MolarMass; 
      Console.Clear(); 
      Console.WriteLine("Moles Calaculator\n\n"); 
      Console.Write("Your sample has "); 
      Console.Write(Moles); 
      Console.Write(" moles\n\n"); 

     } 

     static void EnergyOfWaveCalculator() 
     { 
      Console.Clear(); 
      Console.WriteLine("Energy of Wave Calaculator\n\n"); 
      Console.WriteLine("Please enter the frequency"); 
      double Frequency = Convert.ToDouble(Console.ReadLine()); 
      double PlancksConstant = 6.626e-34; 
      double Energy = PlancksConstant * Frequency; 
      Console.Clear(); 
      Console.WriteLine("Energy of Wave Calaculator\n\n"); 
      Console.Write("The answer is "); 
      Console.Write(Energy); 
      Console.Write(" \n\n"); 

     } 

     static void IdealGasLawCalculator() 
     { 
      Console.Clear(); 
      Console.WriteLine("Ideal Gas Law Calaculator\n\n"); 
      Console.WriteLine("Would you like to solve the following equation for Pressure or Volume? Press v for Volume or p for Pressure"); 
      string Frequency = Console.ReadLine(); 

      if (Frequency == "v"){ 
       Console.Clear(); 
       Console.WriteLine("Ideal Gas Law Calaculator\n\n"); 
       Console.WriteLine("Please enter the pressure"); 
       decimal Pressure = Convert.ToDecimal(Console.ReadLine()); 
       Console.WriteLine("Please enter the the number of moles"); 
       decimal NumberOfMoles = Convert.ToDecimal(Console.ReadLine()); 
       Console.WriteLine("Please enter the the temperature in degrees Kelvin"); 
       decimal TemperatureKelvin = Convert.ToDecimal(Console.ReadLine()); 
       decimal GasLawConstant = Convert.ToDecimal(8.314); 
       decimal IdealGasLaw = NumberOfMoles * GasLawConstant * TemperatureKelvin/Pressure; 
       Console.Clear(); 
       Console.WriteLine("Energy of Wave Calaculator\n\n"); 
       Console.Write("Your answer is "); 
       Console.Write(IdealGasLaw); 
       Console.Write(" \n\n"); 
      } 
      else 
      { 
       Console.Clear(); 
       Console.WriteLine("Ideal Gas Law Calaculator\n\n"); 
       Console.WriteLine("Please enter the volume"); 
       decimal Volume = Convert.ToDecimal(Console.ReadLine()); 
       Console.WriteLine("Please enter the the number of moles"); 
       decimal NumberOfMoles = Convert.ToDecimal(Console.ReadLine()); 
       Console.WriteLine("Please enter the the temperature in degrees Kelvin"); 
       decimal TemperatureKelvin = Convert.ToDecimal(Console.ReadLine()); 
       decimal GasLawConstant = Convert.ToDecimal(8.314); 
       decimal IdealGasLaw = NumberOfMoles * GasLawConstant * TemperatureKelvin/Volume; 
       Console.Clear(); 
       Console.WriteLine("Energy of Wave Calaculator\n\n"); 
       Console.Write("Your answer is "); 
       Console.Write(IdealGasLaw); 
       Console.Write(" \n\n"); 
      } 

     } 
    } 
} 
+0

, где вы хотите, чтобы пользователи имеют возможность выбора? –

+0

Это хороший вопрос Микаэль, я точно не знаю, где. Я заканчиваю их расчет из своего первоначального выбора, я хотел бы, чтобы программа спросила, хотят ли они вернуться в меню – Justin

+0

Хорошо, я думаю, что лучше всего сделать новый метод для меню расчета и выполнить его прямо из основного метода и повторного использования вызова для этого метода в качестве выбора в конце вычислений. Проверьте ответ –

ответ

2

Это довольно просто. У вас была правильная идея.

bool shouldContinue = true; 
while(shouldContinue){ 
     Console.WriteLine("Press 1 for the Density Calculator"); 
     Console.WriteLine("Press 2 for the Moles Calculator"); 
     Console.WriteLine("Press 3 for the Energy of a Wave Calculator"); 
     Console.WriteLine("Press 4 for the Ideal Gas Law Calculator\n\n"); 
     Console.WriteLine("Press 5 to exit"); 
     Console.WriteLine("Please enter a Number from the Options above"); 
     string choice = Console.ReadLine(); 

     switch (choice) 
     { 
      case "1": 
       DensityCalculator(); 
       break; 
      case "2": 
       MolesCalculator(); 
       break; 
      case "3": 
       EnergyOfWaveCalculator(); 
       break; 
      case "4": 
       IdealGasLawCalculator(); 
       break; 
      case "5": 
      shouldContinue = false; 
       break; 
     } 

} 
+1

Большое спасибо! – Justin

0

Вы можете определить новый метод Menu

Поместите код меню там, а затем просто позвонить на него, когда вам это нужно. В конце Main() вы можете использовать простой, если случай

Console.WriteLine("Type 'exit' to quit"); 
if(Console.ReadLine() == "exit") 
{ 

}else 
{ 
    Menu(); 
} 
2

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

Изменить код в Main:

char action = 'Y';  //create varible for user choice (continue or not) 
while (action == 'Y') // add loop 
{ 
    Console.Clear(); 
    Console.WriteLine("Welcome to the Chemistry Formula Calculator!\n\n\n"); 

    Console.WriteLine("Press 1 for the Density Calculator"); 
    Console.WriteLine("Press 2 for the Moles Calculator"); 
    Console.WriteLine("Press 3 for the Energy of a Wave Calculator"); 
    Console.WriteLine("Press 4 for the Ideal Gas Law Calculator\n\n"); 
    Console.WriteLine("Please enter a Number from the Options above"); 
    string choice = Console.ReadLine(); 

    switch (choice) 
    { 
     case "1": 
      DensityCalculator(); 
      break; 
     case "2": 
      MolesCalculator(); 
      break; 
     case "3": 
      EnergyOfWaveCalculator(); 
      break; 
     case "4": 
      IdealGasLawCalculator(); 
      break; 
    } 

    //add these lines 
    Console.WriteLine("Do you want to continue!\n\n\n");   
    Console.WriteLine("Press Y to continue"); 
    Console.WriteLine("Press N to finish");  
    action = Console.ReadKey().KeyChar; 
} 

Или лучше вариант:

Поместите весь код из Main внутри некоторого метода (т.е. Start()), а затем в Main:

char action = 'Y'; 
while (action == 'Y') 
{ 
    Start(); 

    Console.WriteLine("Do you want to continue!\n\n\n");   
    Console.WriteLine("Press Y to continue"); 
    Console.WriteLine("Press N to finish");  
    action = Console.ReadKey().KeyChar; 
} 
+1

спасибо! – Justin

0

Измените свой код следующим образом: в основном методе слишком много кода:

static void Main(string[] args) 
{ 
    ChooseCalculationMenu(); 
} 

public void ChooseCalculationMenu() 
{ 
    // Put the code from Main here instead 
} 

и в конце каждого метода расчета:

Console.WriteLine("Press c to continue or q to quit."); 
if (Console.Readline() == "q"); 
{} 
else 
{ 
    ChooseCalculationMenu(); 
}