I'm creating a C# program for the Currency Converter by console.
At the end I would to insert "Continue? (yes/no)". Here the user have to chose. I've tried this but it doesn't work
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
Console.ReadLine();
string risposta = Console.ReadLine();
do
{
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
break;
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
break;
}
} while (risposta == "N");
you want something like that
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
do
{
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
Console.ReadLine();
string risposta = Console.ReadLine();
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
break;
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
break;
}
} while (risposta == "N");
but that's just a sample, you need to give more information so i'll give you better example. what does your code supposed to do? what other option does the user have? and so on
float Dollaro = 1.32f, Euro, Cambio;
string EuroStr;
ConsoleKeyInfo risposta;
do
{
Console.Write ( "Euro: " );
EuroStr = Console.ReadLine ();
bool result = Single.TryParse ( EuroStr, out Euro );
if ( result )
{
Cambio = Dollaro * Euro;
Console.WriteLine ( "Dollaro: " + Cambio );
} else {
Console.WriteLine ( "Please enter a number" );
}
bool check = false;
do {
Console.Write ( "\nVuoi continuare? (yes/no) " );
risposta = Console.ReadKey ( true );
check = !( ( risposta.Key == ConsoleKey.Y ) || ( risposta.Key == ConsoleKey.N ) );
} while ( check );
switch ( risposta.Key )
{
case ConsoleKey.Y: Console.WriteLine ( "Yes" ); break;
case ConsoleKey.N: Console.WriteLine ( "No" ); break;
}
} while ( risposta.Key != ConsoleKey.N );
I've changed some things:
if I enter a character for the Euro - FormatException msdn. So I've added a TryParse();
I've changed the response from string to ConsoleKeyInfo msdn - this makes the check for "Y" or "N" easier and I think clearer, and there is no need to cast the user input with ToLower() msdn and compare it with a string;
also a check if the user presses "Y" or "N", while the input is different, the same message will appear - Console.Write ( "\nVuoi continuare? (yes/no) " );
In general you should filter all data\info ( whatever ) comes from the user, to avoid exception.
You should move code where you do operation to do while loop.
Try this:
static void Main(string[] args)
{
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
string risposta = "Y";
do
{
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
risposta = Console.ReadLine();
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
}
} while (risposta == "Y");
}
This should fix your problem:
And you should make your variable "risposta" ToLower so that it doesnt matter if you type a small or big letter (y or Y)
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
string risposta = "Y";
do
{
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
risposta = Console.ReadLine();
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
}
} while (risposta.ToLower() == "y");
You need to 'read' answer to be able to test it.
answer = Console.ReadLine();
You can try this, you can also add "else" statements for other key presses.
string key = "";
do
{
Console.Write("Enter Username: ");
username = Console.ReadLine();
Console.Write("Is this correct? (Y/N): ");
key = Console.ReadLine();
if (key.Equals("Y") | key.Equals("y"))
{
break;
}
} while (true);
Try this code:
int num1, num2;
char oPt;
string Count;
do
{
Console.WriteLine("Enter 1st Value");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter 2nd Value : ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" + - * / ");
oPt = Convert.ToChar(Console.ReadLine());
if (oPt == '-')
{
Console.WriteLine("Result: " + (num1 - num2));
}
else if (oPt == '+')
{
Console.WriteLine("Result: " + (num1 + num2));
}
else if (oPt == '*')
{
Console.WriteLine("Result: " + (num1 * num2));
}
else if (oPt == '/')
{
Console.WriteLine("Result: " + (num1 / num2));
}
do
{
Console.WriteLine("Do you wish to calculate another? Yes (y) or No (n): ");
Count = Console.ReadLine();
var CountLower = Count?.ToLower();
if ((CountLower == "y") || (CountLower == "n"))
break;
} while (true );
} while (Count != "n");
}
Related
using System;
namespace LabExer2_CMS
{
class Program
{
double fnum;
double snum;
double answer;
string str;
static void Main(string[] args)
{
double fnum;
double snum;
double answer;
string str;
Console.WriteLine("CALCULATOR");
Console.WriteLine(" ");
Console.WriteLine("First Number: ");
fnum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Select an operator: (+, -, * )");
str = Console.ReadLine();
Console.WriteLine("Second Number: ");
snum = Convert.ToInt32(Console.ReadLine());
if (str == "+")
{
answer = fnum + snum;
Console.WriteLine("The answer is: "+answer);
}
if (str == "-")
{
answer = fnum - snum;
Console.WriteLine("The answer is: "+answer);
}
if (str == "*")
{
answer = fnum * snum;
Console.WriteLine("The answer is: " + answer);
}
Console.Write("PRESS ENTER TO EXIT");
Console.ReadKey();
}
}
}
The first answer is better, but if it's hard to understand, you may try this one.
You may wrap the lines with Console.ReadLine() in try {} catch {} operator, then you need to initialize fnum and snum when you declare them. And you should check the operator as well.
static void Main(string[] args)
{
double fnum = 0;
double snum = 0;
double answer;
string str;
Console.WriteLine("CALCULATOR");
Console.WriteLine(" ");
Console.WriteLine("First Number: ");
try
{
fnum = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Error!");
return;
}
Console.WriteLine("Select an operator: (+, -, * )");
str = Console.ReadLine();
if (str != "+" && str != "-" && str != "*")
{
Console.WriteLine("Wrong operator!");
return;
}
Console.WriteLine("Second Number: ");
try
{
snum = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Error!");
return;
}
if (str == "+")
{
answer = fnum + snum;
Console.WriteLine("The answer is: " + answer);
}
if (str == "-")
{
answer = fnum - snum;
Console.WriteLine("The answer is: " + answer);
}
if (str == "*")
{
answer = fnum * snum;
Console.WriteLine("The answer is: " + answer);
}
Console.Write("PRESS ENTER TO EXIT");
Console.ReadKey();
}
if it helps you
using System;
namespace LabExer2_CMS
{
class Program
{
double fnum;
double snum;
double answer;
string str;
/// <summary>
/// Used instead of the original:
///
/// Console.WriteLine("First Number: ");
/// fnum = Convert.ToInt32(Console.ReadLine());
///
/// resp.
///
/// Console.WriteLine("Second Number: ");
/// snum = Convert.ToInt32(Console.ReadLine());
///
/// </summary>
static double getDouble(string msg) {
double res = 0;
string input = "";
bool isOk = false;
while (!isOk) {
Console.WriteLine(msg);
input = Console.ReadLine();
isOk = double.TryParse(input, out res);
if(!isOk) { Console.WriteLine("Invalid input."); }
}
return res;
}
/// <summary>
/// Used instead of the original:
///
/// Console.WriteLine("Select an operator: (+, -, * )");
/// str = Console.ReadLine();
///
/// </summary>
static string getOperator(string msg1, string[] operators) {
string res = "";
string input = "";
bool isOk = false;
string msg2 = String.Join(",", operators);
string msg = msg1 + "(" + msg2 + ") ";
while (!isOk) {
Console.WriteLine(msg);
input = Console.ReadLine();
isOk = Array.IndexOf(operators, input) >= 0;
if(!isOk) { Console.WriteLine("Invalid input."); }
}
return res;
}
static void Main(string[] args)
{
double fnum;
double snum;
double answer;
string str;
Console.WriteLine("CALCULATOR");
Console.WriteLine(" ");
fnum = getDouble("First Number: ");
string[] operators = new string [] {"+", "-", "*"};
str = getOperator("Select an operator: ", operators);
snum = getDouble("Second Number: ");
if (str == "+")
{
answer = fnum + snum;
Console.WriteLine("The answer is: "+answer);
}
if (str == "-")
{
answer = fnum - snum;
Console.WriteLine("The answer is: "+answer);
}
if (str == "*")
{
answer = fnum * snum;
Console.WriteLine("The answer is: " + answer);
}
Console.Write("PRESS ENTER TO EXIT");
Console.ReadKey();
}
}
}
I have a C# calculator I'm trying to get to run however I keep running into problems, particularly with my last function and currently get stuck in an infinite validation loop, how can I make this work as intended which is to take two numbers and based on user input get the answer for their equation.
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello User what is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name + " Please enter in a number");
Console.ReadLine();
Console.WriteLine("Please enter a Math Operator: +, -, *, / ");
string beta = IsValidSymbol();
string equation = Console.ReadLine();
string useint1 = Console.ReadLine();
string useint2 = Console.ReadLine();
Console.WriteLine("Please enter another number");
Console.WriteLine(MathSymbols(equation,useint1,useint2));
}
public static double Validation()
{
string numbString = Console.ReadLine();
double numbVerify;
while (!double.TryParse(numbString, out numbVerify))
{
Console.WriteLine("please only enter in numbers and do not leave blank");
numbString = Console.ReadLine();
}
return numbVerify;
}
private static string IsValidSymbol()
{
string mathValidation = Console.ReadLine();
while ((String.IsNullOrEmpty(mathValidation)))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter a Math Operator: +, -, *, / ");
mathValidation = Console.ReadLine();
}
return mathValidation;
}
private static double MathSymbols(string e, string useint1,string useint2)
{
useint1 = Console.ReadLine();
useint2 = Console.ReadLine();
double result;
double userinput1;
double userinput2;
while (!double.TryParse(useint1, out userinput1))
{
Console.WriteLine("please type in a number");
useint1 = Console.ReadLine();
}
while (!double.TryParse(useint2, out userinput2))
{
Console.WriteLine("please type in a number");
useint1 = Console.ReadLine();
}
if (e == "+")
{
result = userinput1 + userinput2;
}
else if (e == "-")
{
result = userinput1 - userinput2;
}
else if (e == "*")
{
result = (userinput1 * userinput2);
}
else if (e == "/")
{
result = (userinput1 / userinput2);
}
result = 0;
return result;
}
}
}
In many places you had an unnecessary call to Console.ReadLine and overriding variables. Also you didn't use your method Validation (think about renaming it to GetValidNumber).
I corrected your code to work for valid input. You still need additional validations and refactoring in your code, good luck!
using System;
namespace CalculatorExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello User what is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name + " Please enter in a number");
double useint1 = Validation();
Console.WriteLine("Please enter a Math Operator: +, -, *, / ");
string equation = IsValidSymbol();
Console.WriteLine($"You equation symbol: {equation}");
Console.WriteLine("Please enter another number");
double useint2 = Validation();
double result = MathSymbols(equation, useint1, useint2);
Console.WriteLine($"Result: {result}");
Console.ReadKey();
}
public static double Validation()
{
string numbString = Console.ReadLine();
double numbVerify;
while (!double.TryParse(numbString, out numbVerify))
{
Console.WriteLine("please only enter in numbers and do not leave blank");
numbString = Console.ReadLine();
}
return numbVerify;
}
private static string IsValidSymbol()
{
string mathValidation = Console.ReadLine();
while ((String.IsNullOrEmpty(mathValidation)))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter a Math Operator: +, -, *, / ");
mathValidation = Console.ReadLine();
}
return mathValidation;
}
private static double MathSymbols(string equation, double useint1, double useint2)
{
if (equation == "+")
return useint1 + useint2;
if (equation == "-")
return useint1 - useint2;
if (equation == "*")
return useint1 * useint2;
if (equation == "/")
return useint1 / useint2;
throw new InvalidOperationException($"Unrecognized equation symbol: {equation}");
}
}
}
Console.WriteLine('What is your name, traveler?');
string mainName = Console.ReadLine();
Console.WriteLine('So, your name is ' + mainName + ' ? y/n');
char ans = Console.ReadKey;
if (ans == y)
{
Console.WriteLine('Nice, let me introduce myself now.');
}
else if(ans == n)
{
}
else
{
Console.WriteLine('Please insert either y or n.');
}
In the code above, how can I make it so that the else if statement will return to the third line and the else statement will return to the first line of the code and continue running from there?
You can try to use do....While(true) loop
Console.WriteLine("What is your name, traveler?");
string mainName = Console.ReadLine();
Console.WriteLine("So, your name is " + mainName + " ? y/n");
do
{
var ans = Console.ReadKey(true).Key;
if (ans == ConsoleKey.Y)
{
Console.WriteLine("Nice, let me introduce myself now.");
break;
}
else if (ans == ConsoleKey.N)
{
break;
}
Console.WriteLine("Please insert either y or n.");
} while (true);
Note
I would use Console.ReadKey(true).Key to get keyboard input value,because it's enum.
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 4 years ago.
I am very new to programming as a whole and C# is my first language. I have been working on this project for the past few weeks or so that gives the user 3 options of whether they want to use a random number generator, calculator or roll a dice.
So far everything is going okay. I have been focusing quite a lot on exception handling and commenting to make sure that everything is as clear as possible. One problem that I have come across and am not surer how to fix is that in my dice rolling procedure it prints out the same random dice number x times rather than printing out different random numbers each time. So if you could help me fix that that would be awesome. Here is just the code for that;
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
Also, as I'm a newbie in general, I think some feedback from more experienced users will benefit me as a whole. Is there any mistakes I've made> Any informal rules I have broken? Please let me know I will be very thankful. Here is all of the code;
static void Main(string[] args)
{
Boolean chooseRun = false;
while (chooseRun == false)
{
Console.WriteLine("To use the calculator enter C\nTo use the random number generator enter R\nTo roll a dice enter D");
string chooseProc = Console.ReadLine();
if (chooseProc == "C" || chooseProc == "c")
{
calculator();
chooseRun = true;
}
else if (chooseProc == "R" || chooseProc == "r")
{
numGenerator();
chooseRun = true;
}
else if (chooseProc == "D" || chooseProc == "d")
{
rollDice();
chooseRun = true;
}
else
{
Console.WriteLine("Sorry that was an invalid input. Please try again");
chooseRun = false;
}
}
Console.Write("Goodbye");
Console.ReadKey();
}
/// <summary>
/// Here I have a simple calculator that can do basic functions such as subtraction and then I give them the option to use it again
/// </summary>
static void calculator()
{
int loop = 1;
while (loop == 1)
{
Console.WriteLine("You chose to use the calculator!\nPress the enter key to start"); //Greet the user and give them the option of when they want to start the calculator based upon when they choose to click the enter key
Console.ReadKey(true);
int num1 = 0; //Declaring variables
int num2 = 0;
string operation = "";
int answer;
Boolean gotnum1 = false;
while (gotnum1 == false)
{
Console.Write("Enter the first number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num1 = int.Parse(Console.ReadLine());
gotnum1 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotnum2 = false;
while (gotnum2 == false)
{
Console.Write("Enter the second number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num2 = int.Parse(Console.ReadLine());
gotnum2 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotOpr = false;
while (gotOpr == false)
{
Console.Write("Ok now enter your operation ( x , / , +, -) ");
operation = Console.ReadLine();
switch (operation)
{
case "x":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "X":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "/":
try
{
answer = num1 / num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
}
catch (DivideByZeroException e)
{
Console.WriteLine("You cannot divide by zero");
}
break;
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
default:
Console.WriteLine("Sorry that is an invalid input");
gotOpr = false;
break;
}
}
Console.WriteLine("Do you want to use the calculator again? Select;\nIf you would please enter /Y/\nIf not please enter /N/");
string rerun = Console.ReadLine();
if (rerun.ToUpper() == "N")
{
loop = 0;
}
}
}
/// <summary>
/// This procedure generates a random number and gives the user the option as to whether they would like to generate another
/// </summary>
static void numGenerator()
{
Console.WriteLine("You chose to use the random number generator");
Boolean moreNum = false;
while (moreNum == false)
{
Random r = new Random();
int n = r.Next();
Console.WriteLine(n);
Console.WriteLine("If you would like another number enter Y, otherwise please enter N");
string rerun = Console.ReadLine();
if (rerun == "Y" || rerun == "y")
{
moreNum = false;
}
else if (rerun == "N" || rerun =="n")
{
moreNum = true;
}
}
}
/// <summary>
/// In this procedure a virtual dice is rolled of a user inputted number of times, this too gives the user the option to roll the dice again after rolling it x times
/// </summary>
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
You should create the Random object only once, typically create is in a static field (if you create it many times, it would generate the same values every time)
static Random rnd = new Random();
I am new to Console Application, I usually use C# for Unity. The code doesn't really work how I want it
Yes I know using Goto isn't good. But I don't know alternatives
I had [ a = 2 ] [ b = 3 ] and [ ans = a+b ] so the obvious answer is 5. So when you put 5 it runs the Else statement which is getting it incorrect.
goto start;
error:
Console.Clear();
Console.WriteLine("Input not Recognized");
Console.WriteLine("Try Again");
Console.WriteLine("\nType (Reset) to Reset Program");
Console.WriteLine("\nType (End) to End Program");
Console.WriteLine("");
string error1 = Console.ReadLine();
if (error1.Equals("reset", StringComparison.InvariantCultureIgnoreCase))
{
goto start;
}
if (error1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
{
goto error;
}
start:
Console.WriteLine("Solve the Math Equation");
int a = 2;
int b = 3;
int ans = a + b;
Console.WriteLine("\n2 + 3");
Console.WriteLine("");
string user = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
user += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && user.Length > 0)
{
user = user.Substring(0, (user.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
if (user.Equals(ans))
{
Console.Clear();
Console.WriteLine("Correct!");
Console.WriteLine("\nYour answer " + ans);
Console.WriteLine("\nType (End) to End Program");
Console.WriteLine("");
string end1 = Console.ReadLine();
if (end1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
{
goto error;
}
}
else
{
Console.Clear();
Console.WriteLine("Incorrect!");
Console.WriteLine("\nThe answer was " + ans);
Console.WriteLine("\nType (Reset) to Reset Program");
Console.WriteLine("Type (End) to End Program");
Console.WriteLine("");
string rne1 = Console.ReadLine();
if (rne1.Equals("reset", StringComparison.InvariantCultureIgnoreCase))
{
Console.Clear();
goto start;
}
if (rne1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
goto error;
Your user and ans are not equal in your code which is why your code jumps to the error. The reason why they are not equal are their Types.
user is a string
ans is an integer
So you are comparing "5" to 5 and that can not be equal.
Convert one of the variables so you have the same type.
Either use user.Equals(ans.ToString()) in the if statement or convert the string to a number (which is the better solution IMO - because it also handles the situation when the input is not a number). Like this:
int userAns;
if (!Int32.TryParse(user, userAnsj))
Console.WriteLine("Input is not a valid integer.");
and then comapare userAns to ans.