I'm a beginner c# programmer trying to program a simple app that shows a menu to the user. When option 1 is selected by the user at run-time, the program lists values from 0 to 100 Celsius degrees converted to Fahrenheit degrees. When option 2 is chosen, the program calculates and displays a list of values between 0 and 212 degrees in Fahrenheit converted to Celsius degrees. Use a constant for the values 100 and 212 in the related method.
The problem is that I'm only getting the option entered not a converted result. This is what I have done so far:
{
class TemperatureConverter
{
private const int columns = 1;
/// <summary>
///
///
///
/// </summary>
public TemperatureConverter()
{
Start();
}
/// <summary>
///
/// </summary>
public void Start()
{
while (true)
{
int choice = ShowMenu();
switch (choice)
{
case 0:
return;
case 1:
Console.WriteLine();
while (true)
{
Console.Write("Enter Celsius:");
Console.WriteLine();
if (double.TryParse(Console.ReadLine(), out double celsius))
{
Console.WriteLine(ShowTableCelsiusToFahrenheit(celsius));
Console.WriteLine();
break;
}
}
break;
case 2:
Console.WriteLine();
while (true)
{
Console.Write("Enter Fahrenheit:");
if (double.TryParse(Console.ReadLine(), out double fahrenheit))
{
Console.WriteLine(ShowTableFahrenheitToCelsius(fahrenheit));
Console.WriteLine();
break;
}
}
break;
default:
Console.WriteLine("You must enter 1 to convert to Celsius or 2 to convert to Fahrenheit or 0 to exit!");
break;
}
}
}
private double CelsiusToFarenheit(double celsius) => celsius * 9.0 / 5.0 + 32.0;
private double FahrenheitToCelsius(double fahrenheit) => (fahrenheit - 32.0) * 5.0 / 9.0;
private string ShowTableCelsiusToFahrenheit(double celsius) => $"{celsius}°C is {CelsiusToFarenheit(celsius)}°F";
private string ShowTableFahrenheitToCelsius(double fahrenheit) => $"{fahrenheit}°F is {FahrenheitToCelsius(fahrenheit)}°C";
public int ShowMenu()
{
int width = 28;
while (true)
{
Console.WriteLine("MAIN MENU");
Console.WriteLine("".PadLeft(width, '-'));
Console.WriteLine("Celsius to Fahrenheit".PadRight(width - 3) + ": 1");
Console.WriteLine("Fahrenheit to Celsius".PadRight(width - 3) + ": 2 ");
Console.WriteLine("Exit the program".PadRight(width - 3) + ": 0 ");
Console.WriteLine("".PadLeft(width, '-'));
Console.WriteLine();
Console.WriteLine("Your choice: ");
string line = Console.ReadLine();
if (int.TryParse(line, out int choice))
{
return choice;
}
}
}
}
}
I've done some refactoring for you so that you can see how this kind of code can be written. I've tried to logically extract the parts so there is a clear responsibility and flow for each part of the program.
I've also removed the automatic running of the code from the constructor. It's a bad idea to run code in the constructor other than code to set the initial conditions of the class.
Here's the refactored code:
void Main()
{
var tc = new TemperatureConverter();
tc.Start();
}
class TemperatureConverter
{
public void Start()
{
while (true)
{
int choice = ShowMenu();
switch (choice)
{
case 0:
return;
case 1:
Console.WriteLine();
while (true)
{
Console.Write("Enter Celsius:");
if (double.TryParse(Console.ReadLine(), out double celsius))
{
Console.WriteLine(GetCelsiusToFahrenheitLine(celsius));
Console.WriteLine();
break;
}
}
break;
case 2:
Console.WriteLine();
while (true)
{
Console.Write("Enter Fahrenheit:");
if (double.TryParse(Console.ReadLine(), out double fahrenheit))
{
Console.WriteLine(GetFahrenheitToCelsiusLine(fahrenheit));
Console.WriteLine();
break;
}
}
break;
default:
Console.WriteLine("You must enter 1 to convert to Celsius or 2 to convert to Fahrenheit or 0 to exit!");
break;
}
}
}
private double CelsiusToFarenheit(double celsius) => celsius * 9.0 / 5.0 + 32.0;
private double FahrenheitToCelsius(double fahrenheit) => (fahrenheit - 32.0) * 5.0 / 9.0;
private string GetCelsiusToFahrenheitLine(double celsius) => $"{celsius}°C is {CelsiusToFarenheit(celsius)}°F";
private string GetFahrenheitToCelsiusLine(double fahrenheit) => $"{fahrenheit}°F is {FahrenheitToCelsius(fahrenheit)}°F";
public int ShowMenu()
{
int width = 28;
while (true)
{
Console.WriteLine("MAIN MENU");
Console.WriteLine("".PadLeft(width, '-'));
Console.WriteLine("Celsius to Fahrenheit".PadRight(width - 3) + ": 1");
Console.WriteLine("Fahrenheit to Celsius".PadRight(width - 3) + ": 2 ");
Console.WriteLine("Exit the program".PadRight(width - 3) + ": 0 ");
Console.WriteLine("".PadLeft(width, '-'));
Console.WriteLine();
Console.WriteLine("Your choice: ");
string line = Console.ReadLine();
if (int.TryParse(line, out int choice))
{
return choice;
}
}
}
}
Now, this doesn't do what has been asked of you in the text in your question. I'll leave that to you. One hint on that - there is no need to read in any temperature as input from the user.
Related
I am making an interface to store character and dinosaur variables to a list and then print them out when asked.
There is a switch statement to take the users' inputs:
Case 1: The function allows the user to input character data and then it's put into a list.
Case 2.: The function allows the user to input dinosaur
data and then it put into a list.
Case 3 The function prints the objects in each list. However, whenever I run it it doesn't print anything and comes up with no errors. If I run the code to print each list in their respective case then they print out fine.
class Program
{
static void Main()
{
int NumAns;
Console.WriteLine("*1. Character Creator ");
Console.WriteLine("*2. Dinosaur Creator ");
Console.WriteLine("*3. Display ");
Console.WriteLine("");
Console.WriteLine("Specify your menu choice");
string NumAnsString = Console.ReadLine();
NumAns = Convert.ToInt32(NumAnsString);
MenuChosen(NumAns);
}
static void MenuChosen(int selection)
{
List<Dinosaur> Dinosaur_l = new List<Dinosaur>();
List<Character> CharSave = new List<Character>();
Character character = new Character();
Dinosaur dinosaur = new Dinosaur();
switch (selection)
{
case 1:
Console.WriteLine("You chose Character Creator");
character.CharacterVal();
CharSave.Add(new Character
{
name = character.name,
age = character.age,
height = character.height,
hair = character.hair,
eyes = character.eyes,
glasses = character.glasses
});
Main();
break;
case 2:
Console.WriteLine("You chose Dinosaurs");
dinosaur.DinoVal();
Dinosaur_l.Add(new Dinosaur
{
name = dinosaur.name,
species = dinosaur.species,
diet = dinosaur.diet,
sex = dinosaur.sex
});
Main();
break;
case 3:
Console.WriteLine(" ");
Console.WriteLine("Character: ");
Console.WriteLine(" ");
foreach (Character chara in CharSave)
{
Console.WriteLine(chara.name);
Console.WriteLine(chara.age);
Console.WriteLine(chara.height);
Console.WriteLine(chara.hair);
Console.WriteLine(chara.eyes);
Console.WriteLine(chara.glasses);
}
Console.WriteLine(" ");
Console.WriteLine("Dinosaurs: ");
Console.WriteLine(" ");
foreach (Dinosaur Dino in Dinosaur_l)
{
Console.WriteLine(Dino.name);
Console.WriteLine(Dino.species);
Console.WriteLine(Dino.diet);
Console.WriteLine(Dino.sex);
}
Console.WriteLine(" ");
Main();
break;
}
}
}
This is the code used for CharacterVal function
public class Character
{
public string name;
public string age;
public string height;
public string hair;
public string eyes;
public string glasses;
public int charID = 0;
int x = 1;
public void CharacterVal()
{
charID++;
Console.WriteLine("Name your Character: ");
name = Console.ReadLine();
Console.WriteLine("How old is " + name + "? :");
age = Console.ReadLine();
Console.WriteLine("How tall is " + name + "?: ");
height = Console.ReadLine();
Console.WriteLine("What colour is " + name + "'s hair ?: ");
hair = Console.ReadLine();
Console.WriteLine("What colour is " + name + "'s eyes ?: ");
eyes = Console.ReadLine();
GlassesCheck();
}
public void GlassesCheck()
{
Console.WriteLine("does " + name + " wear glasses? (yes/no): ");
while (x == 1)
{
glasses = Console.ReadLine();
if(glasses =="yes")
{
x = 2;
}
else if(glasses == "no")
{
x = 2;
}
else
{
x = 1;
Console.WriteLine("'"+glasses+"' is not a valid answer, does " + name + " wear glasses? (yes/no): ");
}
}
}
}
This is the code used for the DinoVal function
public class Dinosaur
{
public string species;
public string diet;
public string sex;
public string name;
public void DinoVal()
{
Console.WriteLine("***************************");
Console.WriteLine("*Choose a Dinosaur *");
Console.WriteLine("* *");
Console.WriteLine("*1. Alvarezsaurus *");
Console.WriteLine("*2. Avimimus *");
Console.WriteLine("*3. Bactrosaurus *");
Console.WriteLine("*4. Baryonyx *");
Console.WriteLine("*5. Coloradisaurus *");
Console.WriteLine("*6. Chungkingosaurus *");
Console.WriteLine("***************************");
int Selection = Convert.ToInt32(Console.ReadLine());
switch (Selection)
{
case 1:
Console.WriteLine("you have chosen the Alvarezsaurus");
Console.WriteLine("This is a Carnivore ");
species = "Alvarezsaurus";
diet = "Carnivore";
break;
case 2:
Console.WriteLine("you have chosen the Avimimus");
Console.WriteLine("This is an Omnivore ");
species = "Avimimus";
diet = "Omnivore";
break;
case 3:
Console.WriteLine("you have chosen the Bactrosaurus");
Console.WriteLine("This is a Herbivore ");
species = "Bactrosaurus";
diet = "Herbivore";
break;
case 4:
Console.WriteLine("you have chosen the Baryonyx");
Console.WriteLine("This is a Carnivore ");
species = "Baryonyx";
diet = "Carnivore";
break;
case 5:
Console.WriteLine("you have chosen the Coloradisaurus");
Console.WriteLine("This is an Omnivore ");
species = "Coloradisaurus";
diet = "Omnivore";
break;
case 6:
Console.WriteLine("you have chosen the Chungkingosaurus");
Console.WriteLine("This is a Herbivore ");
species = "Chungkingosaurus";
diet = "Herbivore";
break;
}
Console.WriteLine("Please choose the dinosaurs sex");
Console.WriteLine("1.Male");
Console.WriteLine("2.Female");
int GenderChoice = Convert.ToInt32(Console.ReadLine());
switch (GenderChoice)
{
case 1:
Console.WriteLine("the dinosaur will be male");
sex = "Male";
break;
case 2:
Console.WriteLine("the dinosaur will be female");
sex = "Female";
break;
}
Console.WriteLine("What name will you give this " + sex + " " + species + " ?:");
name = Console.ReadLine();
}
}
i've tried moving
CharSave.Add(new Character
{
name = character.name,
age = character.age,
height = character.height,
hair = character.hair,
eyes = character.eyes,
glasses = character.glasses
});
into case 3 but all that does is print blank spaces for each object
The lists that store the characters and the dinos need to be outside of the MenuChosen method because as you code is written everytime MenuChosen is called new lists are created.
You could:
class Program
{
static List<Dinosaur> Dinosaur_l = new List<Dinosaur>();
static List<Character> CharSave = new List<Character>();
}
Main -> MenuChosen -> Main -> MenuChosen -> ...
Because the way you structured (Main calls MenuChosen which calls Main and so on) your code - if you run the game for long enough - will get end up with a stack overflow.
To avoid this you can run your code in a loop:
Main()
{
while (true) // or selection was 'Quit', etc.
{
your code here
}
// Remove calls to 'Main' from the switch statement.
When I run this console app, everything works fine but except for my UserAnswer() result. It keeps returning a value of '0' for both num1 & num2. This doesn't make sense to me because I don't receive any errors for declaring a new value for num1 & num2 in Input1() & Input2() methods. It compiles and runs fine but why is it not picking up the new values of these variables?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatorApp
{
public class Program
{
float Number;
float num2;
float num1;
public static void Main(string[] args)
{
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
//Console.ReadKey();
// execute program functions
new Program().Input1();
new Program().Input2();
new Program().UserOption();
new Program().UserAnswer();
new Program().PromptUserExit();
}
// Ask the user to type the first number.
//Console.WriteLine("Type a number, and then press Enter");
public float Input1() {
Console.WriteLine("Type a number, and then press Enter");
bool Valid = false;
while (Valid == false)
{
string Input = Console.ReadLine();
if (!float.TryParse(Input, out Number))
{
Console.WriteLine("Not an integer, please try again.");
}
else
{
Valid = true;
num1 = (float)Convert.ToDecimal(Input);
}
} return num1;
}
public float Input2() {
// Ask the user to type the second number.
Console.WriteLine("Type another number, and then press Enter");
bool Valid2 = false;
while (Valid2 == false)
{
string Input2 = Console.ReadLine();
if (!float.TryParse(Input2, out Number))
{
Console.WriteLine("Not an integer, please try again.");
}
else
{
Valid2 = true;
num2 = (float)Convert.ToDecimal(Input2);
}
} return num2;
}
public void UserOption() {
// Ask the user to choose an option.
Console.WriteLine("Choose an option from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
}
public void UserAnswer() {
bool isOperatorValid;
do
{
isOperatorValid = true;
switch (Console.ReadLine())
{
case "a":
Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2));
break;
case "s":
Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));
break;
case "m":
Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2));
break;
case "d":
Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
break;
default:
Console.WriteLine("Invalid input please try again");
isOperatorValid = false;
break;
}
} while (!isOperatorValid);
}
public void PromptUserExit() {
// Wait for the user to respond before closing.
Console.Write("Press any key to close the Calculator console app...");
Console.ReadKey();
}
}
}
This is your problem:
new Program()
You are creating a new instance of the Program class every time you call a method. Each time, the variables are initialized with the default value of 0.
You need to initialize the class once, then use the same class:
var program = new Program();
program.Input1();
program.Input2();
program.UserOption();
program.UserAnswer();
program.PromptUserExit();
Or you could just make all of your methods and variables static so that you can call them directly without initializing a new object. In bigger programs, you would want to be careful with declaring things static (there is a time and place, but it's not "always"). But in a small program like this, it's fine.
This is literally my first program I've ever written (started learning this past Monday); I am a total newbie.
My question is, how can I prevent exceptions from being thrown when a user enters an invalid character when the program prompts the user for fahreinheit or celsius entry (expecting a number)??? So for example, when a user enters "asfasd", the program throws an exception.
I did a lot of searching on the site before posting this, and I was successfully able to find other input validation questions, however, they were all concerning C and C++ and since I am such a newbie, I have a hard time with understanding those languages and how they relate to C#. Thank you. Please see code:
using System;
namespace Converter
{
class Program
{
static void Main()
{
float? FahrenheitInput = null;
double? CelsiusInput = null;
float? KilogramInput = null;
float? PoundsInput = null;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
FahrenheitInput = float.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
CelsiusInput = double.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static float? FahrenheitToCelsius(float? INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double? CelsiusToFahrenheit(double? INPUT)
{
return INPUT * 1.8 + 32;
}
}
}
You can either put it in Try-Catch block or use a while loop to validate the user input.
below is your code with a while loop which validates users input.
class Program
{
static void Main(string[] args)
{
double FahrenheitInput = 0;
double CelsiusInput = 0;
double KilogramInput = 0;
double PoundsInput = 0;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
while (!double.TryParse(Console.ReadLine(), out FahrenheitInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
while (!double.TryParse(Console.ReadLine(), out CelsiusInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static double FahrenheitToCelsius(double INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double CelsiusToFahrenheit(double INPUT)
{
return INPUT * 1.8 + 32;
}
}
TryParse is your good friend here. In most scenarios, you should favor using TryParse than Parse. In your example, you can do something like:
int validInt;
int.TryParse(Console.ReadLine(), out validInt);
float validFloat;
float.TryParse(Console.ReadLine(), out validFloat);
Parse vs. TryParse
The easiest way, IMHO, to change the routine is to rewrite Parse into corresponding TryParse:
// UserChoice = int.Parse(Console.ReadLine());
UserChoice = int.TryParse(Console.ReadLine(), out UserChoice) ? UserChoice : -1;
...
A bit more complex (you have to convert float into float?)
// FahrenheitInput = float.Parse(Console.ReadLine());
float v;
FahrenheitInput = float.TryParse(Console.ReadLine(), out v) ? (float?) v : null;
The same scheme for CelsiusInput
// CelsiusInput = double.Parse(Console.ReadLine());
double d;
CelsiusInput = double.TryParse(Console.ReadLine(), out v) d (double?) d : null;
The underlying mechanic of the code is
We try to parse user input TryParse(Console.ReadLine()...
If parse succeeds (and thus TryParse returns true) we just return the out (parsed value).
If parse fails (and thus TryParse returns false) we return some special a value (-1 for UserChoice or null in case of FahrenheitInput or CelsiusInput)
P.S. in the first switch you have just case 1, case 2 and case 5; however, you've put "This is not a valid entry. Please enter 1, 2, 3, 4, or 5." in the error message. It seems, that you have to either implement case 3 and case 4 in the switch or edit the error message.
Use int.TryParse instead of int.Parse and float.tryParse instead of float.Parse
While all the answers provided seem to work, the question you asked was
how can I prevent exceptions from being thrown [..]
and I just want to point out that you do this by putting the part which throws the exception in an try-catch-block. What this does is it executes the code within try until an exception is beeing thrown and then passes this exceptions as a parameter to the catch-part where you can handle it:
EXAMPLE
do
{
try
{
// the code you already have
}
catch (Exception ex)
{
Console.WriteLine("This is no valid input (" + ex.Message + ")! Try again...");
}
} while (UserChoice != 5);
Of course preventing exceptions from beeing thrown at all in the first place is the better way (as all the other answers do suggest), but this approach works as well and ist more generic in case you run into a similar problem in the future. Using switch-case-statements for error-handling is quite common practice...
So i've got this code. I have it so that when the user inputs a number 1-4 it will display a different saying plus their name at the beginning based on which number they input. What i want to do is make it so that when they input a -1 instead of 1, 2, 3 or 4 it allows them to type in their own saying to be output.
using System;
namespace TryIt
{
class Conversation
{
// Declare constants that define the input range
private const int MIN = -1;
private const int MAX = 4;
// Declare constants for the colors to be used
private const ConsoleColor INPUT_COLOR = ConsoleColor.Green;
private const ConsoleColor PROMPT_COLOR = ConsoleColor.Blue;
private const ConsoleColor ERROR_COLOR = ConsoleColor.Red;
private const ConsoleColor MESSAGE_COLOR = ConsoleColor.White;
private const ConsoleColor BACKGROUND_COLOR = ConsoleColor.DarkGray;
private String name;
public Conversation()
{
Console.Title = "The Best TryIt Program";
Console.BackgroundColor = BACKGROUND_COLOR;
Console.Clear();
}
public void go()
{
getName();
int number = getNumber();
displayMessage(number);
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine();
}
private void getName()
{
Console.ForegroundColor = PROMPT_COLOR;
Console.Write("Enter your name. ");
Console.ForegroundColor = INPUT_COLOR;
// This will ask what your name is and prompt you to enter it.
name = Console.ReadLine();
}
private int getNumber()
{
int input;
// int input will take your name and display it back to you
do
{
Console.ForegroundColor = PROMPT_COLOR;
Console.Write("\nEnter a number from 1 to 4. ");
Console.ForegroundColor = INPUT_COLOR;
// This will ask you for a number
input = Convert.ToInt16(System.Console.ReadLine());
// If you don't put in a valid number it will tell you
if (input < MIN || input > MAX)
{
Console.ForegroundColor = ERROR_COLOR;
Console.WriteLine("Invalid Number!");
}
} while (input < MIN || input > MAX);
return input;
}
private void displayMessage(int choice)
{
String phrase = " ";
// Declares the variable (a string) for the output messages.
switch (choice)
{
case 1: phrase = " is a genius!"; break;
case 2: phrase = " is amazing!"; break;
case 3: phrase = " came to chew bubblegum" +
", kick butt " + "and is all out of gum."; break;
case 4: phrase = " is a rockstar!"; break;
}
Console.WriteLine();
Console.ForegroundColor = MESSAGE_COLOR;
// This will display the message you selected 10 times
for (int counter = 0; counter < 10; counter++)
{
Console.WriteLine(counter + ") " + name + phrase);
}
}
}
}
switch(choice)
{
case 1: ...
.
.
.
case -1: Console.WriteLine("Put in your own saying: ");
phrase = " " + Console.ReadLine();
break;
}
This switch case will ask you when typing "-1" to put in the saying and then writes it into phrase. After the switch case you can proceed like in your above code.
So this is my budget calculator.
It calculates how much i can earn with deposit(% per year), i can add money(earnings) and can decrease money(loosing).
In my code you have to manually tell the size of starting money.
What i need is for example in the beginning i tell my program that starting capital is 500euro. When i use deposit, it become for example 570,50. When i use earnings, i need it to start from 570,50, but in my program it will always ask again, what is your starting capital. I need to do it automatically somehow. Sorry for my bad english and here is the whole code :)
class Program
{
static void Main(string[] args)
{
int menu;
do
{
Console.WriteLine("1 - '%'");
Console.WriteLine("2 - '+'");
Console.WriteLine("3 - '-'");
Console.WriteLine("0 - iziet");
Console.Write("Menu: ");
menu = Convert.ToInt32(Console.ReadLine());
if (menu > 0 && menu < 4)
{
switch (menu)
{
case 1:
{
Console.Write("Noguldamā naudas summu: ");
int a = Convert.ToInt32(Console.ReadLine());
Console.Write("Procentu likme (0 - 100): ");
int b = Convert.ToInt32(Console.ReadLine());
Console.Write("Laiks (gadi): ");
int c = Convert.ToInt32(Console.ReadLine());
double d = Procenti(a, b, c);
Console.WriteLine("\nNaudas summa pēc {0} gadiem būs {1}\n", c, d);
}
break;
case 2:
{
Console.Write("Sakuma nauda: ");
int a = Convert.ToInt32(Console.ReadLine());
Console.Write("Cik nopelnijat: ");
int b = Convert.ToInt32(Console.ReadLine());
double d = Pluss(a, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", d);
}
break;
case 3:
{
Console.Write("Sakuma nauda: ");
double a = Convert.ToDouble(Console.ReadLine());
Console.Write("Cik izterejat: ");
double b = Convert.ToDouble(Console.ReadLine());
double d = Minuss(a, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", d);
}
break;
}
}
else
{
Console.WriteLine();
Console.WriteLine("Ludzu ievadiet ciparus 0,1,2,3 - parejie cipari ir arpus robezham!");
Console.WriteLine();
}
} while (menu != 0);
}
//FUNKCIJASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
static double Procenti(double a, double b, int c)
{
for (int i = 0; i < c; i++)
{
a = (a * (b / 100) + a);
}
return a;
}
static double Pluss(double a, double b)
{
return a + b;
}
static double Minuss(double a, double b)
{
return a - b;
}
}
you need to store the value inside a variable.
and before to start the transactions you ask the user for the value :
int menu;
float stored_money;
Console.Write("Enter the Initial Value: ");
stored_money = Convert.ToInt32(Console.ReadLine());
do
{
and in the functions use this variable
static double Pluss(double b)
{
stored_money = stored_money + b;
return stored_money;
}
static double Minuss(double b)
{
stored_money = stored_money - b;
return stored_money;
}
Well, basically it looks like you need to save your balance amount somewhere in your code, because right now you're entering it from console in each menu point.
Something like (note I've omitted most of code):
int menu;
decimal amount;
do
{
.... //your code
case 1:
{
Console.Write("Noguldamā naudas summu: ");
amount = Convert.ToDecimal(Console.ReadLine());
.... //your code
decimal d = Procenti(a, b, c);
amount += d;
}
case 2:
{
Console.Write("Cik nopelnijat: ");
decimal b = Convert.ToInt32(Console.ReadLine());
amount = Pluss(amount, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", amount);
}
.... //your code
} while (menu != 0);
And later in all cases you should not enter amount, but use that saved value and modify it according to menu point task.
Or maybe you even should introduce new menu point to set initial amount and don't enter it in point 1 (if point 1 can be called multiple times) - it depends on your calculator logic and it's up to you.
Note - it's better to use decimal rather that int and double for financial calculations as it is designed to store full possible precision.