how can I parse 2 double values in 1 statement instead of 2 if statements ?
my code :
double a, b;
while (true)
{
if (Double.TryParse(Console.ReadLine(), out a))
{
}
else
{
continue;
}
if (Double.TryParse(Console.ReadLine(), out b))
{
}
else
{
continue;
}
break;
}
I have already searched for it but did not found any good result
Something like this:
if (Double.TryParse(Console.ReadLine(), out a)
&& Double.TryParse(Console.ReadLine(), out b))
{
}
else
{
continue;
}
Note that the if block is only entered if both values are successfully parsed.
The if is redundant here, you don't need it and it makes the code less readable with an unnecessary continue.
double a, b;
while (!(double.TryParse(Console.ReadLine(), out a) &&
double.TryParse(Console.ReadLine(), out b))
{
}
//a and b successfully parsed.
Related
Dear Amateur and Veteran Developers,
I'm a beginner who recently started learning C# a bit more seriously (I've already tipped my toes into the world of C# in high school, but now, I'm more serious about learning it). I've made a simple command prompt application as a homework for my High-level Programming Languages lesson at my university:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HW_002_01
{
class Program
{
static void Main(string[] args)
{
Console.Write("Please enter the length of the triangle's a side (cm)! ");
double a;
bool a_if = double.TryParse(Console.ReadLine(), out a);
Console.Write("Please enter the length of the triangle's b side (cm)! ");
double b;
bool b_if = double.TryParse(Console.ReadLine(), out b);
Console.Write("Please enter the length of the triangle's c side (cm)! ");
double c;
bool c_if = double.TryParse(Console.ReadLine(), out c);
if (a_if == true && a > 0 && b > 0 && c > 0)
{
double res1 = a + b;
if (res1 > c)
{
Console.WriteLine("Triangle equality is present.");
}
else
{
Console.WriteLine("Triangle equality is not present.");
}
}
else if (b_if == true && a > 0 && b > 0 && c > 0)
{
double res2 = a + b;
if (res2 > c)
{
Console.WriteLine("Triangle equality is present.");
}
else
{
Console.WriteLine("Triangle equality is not present.");
}
}
else if (c_if == true && a > 0 && b > 0 && c > 0)
{
double ossz3 = a + b;
if (res3 > c)
{
Console.WriteLine("Triangle equality is present.");
}
else
{
Console.WriteLine("Triangle equality is not present.");
}
}
else
{
Console.WriteLine("You cannot make a tringle with these numbers.");
}
Console.ReadKey();
}
}
}
This little program checks triangle equality in a triangle with the numbers that the user types in. It runs fine, but I just don't know how to make an error message about the program not being able to understand decimal fractions with a dot instead of a comma. This would be a nice cosmetic touch-up to my program to excuse my beginner-level spaghetti code.
I hope someone replies very soon.
double.TryParse already check the number format by using your default culture. So if the dot doesnt exist in your culture number format, and a user inputs it instead of comma, double.TryParse returns false.
I've written a method that will help you make sure that there is a comma and it depends on the read and the operation you did to read and then convert to double. Previously your reading line is:
bool a_if = double.TryParse(Console.ReadLine(), out a);
And now:
bool a_if = double.TryParse(isWithComma(Console.ReadLine()), out a);
In fact, the method will check if the comma is within the number, and if that will show an error message and the program will stop and I have added a red color to give more expression in the error, and at the same time it returns a string if the number is correct and does not contain a comma, then the program will complete without problems
This is the entire code after modification, and there is a variable (ossz3) that has shown me an error and I have modified it, please check it:
using System;
namespace HW_002_01
{
class Program
{
//New by: https://github.com/MohammadYAmmar
public static string isWithComma(string value)
{
if (value.Contains(","))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error: cannot be used comma instead of a dot.");
Console.WriteLine("Please try again using the point (dot) for example 3.3");
System.Environment.Exit(0);
return value;//Won't happen
}
else
{
return value;
}
}
static void Main(string[] args)
{
Console.Write("Please enter the length of the triangle's a side (cm)! ");
double a;
bool a_if = double.TryParse(isWithComma(Console.ReadLine()), out a);
Console.Write("Please enter the length of the triangle's b side (cm)! ");
double b;
bool b_if = double.TryParse(isWithComma(Console.ReadLine()), out b);
Console.Write("Please enter the length of the triangle's c side (cm)! ");
double c;
bool c_if = double.TryParse(isWithComma(Console.ReadLine()), out c);
if (a_if == true && a > 0 && b > 0 && c > 0)
{
double res1 = a + b;
if (res1 > c)
{
Console.WriteLine("Triangle equality is present.");
}
else
{
Console.WriteLine("Triangle equality is not present.");
}
}
else if (b_if == true && a > 0 && b > 0 && c > 0)
{
double res2 = a + b;
if (res2 > c)
{
Console.WriteLine("Triangle equality is present.");
}
else
{
Console.WriteLine("Triangle equality is not present.");
}
}
else if (c_if == true && a > 0 && b > 0 && c > 0)
{
//Old
//double ossz3 = a + b;
//New: Please check that the spelling is correct so that the code is correct for this variable as you wanted it to
double res3 = a + b;
if (res3 > c)
{
Console.WriteLine("Triangle equality is present.");
}
else
{
Console.WriteLine("Triangle equality is not present.");
}
}
else
{
Console.WriteLine("You cannot make a tringle with these numbers.");
}
Console.ReadKey();
}
}
}
Good luck and have a good journey in learning C# :)
This is a simple calculator. It performs calculations. However, every time it calculates I save that total and add it to a running total. But when I type in undo, the running total disappears and the previous calculation is not subtracted from the running total. Can someone please help me? This is suppose to be in memento format. So when I undo, a stack is removed or a total from a previous calculation. I am struggling with that.
class Calculator
{
public Stack<double> result= new Stack<double>();
double total = 0;
public void Add(double a, double b)
{
total += a + b;
Console.WriteLine("Sum:{0}", total);
result.Push(total);
}
public void Sub(double a, double b)
{
total += a - b;
Console.WriteLine("Difference:{0}", total);
result.Push(total);
}
public void Mul(double a, double b)
{
total += a * b;
Console.WriteLine("Product:{0} ", total);
result.Push(total);
}
public void Div(double a, double b)
{
if (b!=0)
{
total += a / b;
Console.WriteLine("Quotient:{0}", total);
result.Push(total);
}
else
{
Console.WriteLine("Error: Cannot divide by 0");
}
}
double GetTotal()
{
return total;
}
void Undo()
{
if (result.Count==0)
{
Console.WriteLine("UNDO IS NOT AVAILABLE");
}
Console.WriteLine("Running total:{0}", total);
}
void clear()
{
while (result.Count !=0)
result.Pop();
total = 0;
Console.WriteLine("Running total:{0}", total);
}
static int Main()
{
Calculator cal=new Calculator();
string line="";
while (true)
{
Console.WriteLine("Enter (Clear, Undo, Exit, Expression):");
if (line.ToLower() == "exit")
break;
else if (line.ToLower() == "undo")
cal.Undo();
else if (line.ToLower() == "clear")
cal.clear();
else
{
double a, b;
Console.WriteLine("Write the first number");
double.TryParse(Console.ReadLine(), out a);
Console.WriteLine("Write the second number");
double.TryParse(Console.ReadLine(), out b);
Console.WriteLine("Write the operand (+, -, /, *)");
char.TryParse(Console.ReadLine(), out char c);
if (c == '+')
cal.Add(a, b);
if (c == '-')
cal.Sub(a, b);
if (c == '*')
cal.Mul(a, b);
if (c == '/')
cal.Div(a, b);
}
}
return 0;
}
There are a couple things you need to fix here.
First, you never assign anything to line, so your code immediately falls into the else block for "Expression". So not only is Undo() not working, but I don't see how the Clear() or Exit() methods could be working either. Something like this will help with that by assigning to line:
while (true)
{
Console.WriteLine("Enter (Clear, Undo, Exit, Expression):");
line = Console.ReadLine();
if (line.ToLower() == "exit")
break;
//Rest of the code left out for simplicity...
}
Note that this considers invalid input as "Expression" and false down the else path, so you might want to consider explicitly checking for line.ToLower() == "expression" and giving an error message otherwise.
Also consider changing to a switch statement. It's not required by any means, but a little easier to maintain and read, IMO. You should also probably do a case-insensitive Equals() with this overload rather than converting the input to lowercase.
As for the actual implementation of your Undo() method, since your last action is just one item down on the Stack, just Pop() the top item off and Peek() at the Stack for your previous total:
void Undo()
{
if (result.Count==0)
{
Console.WriteLine("UNDO IS NOT AVAILABLE");
}
result.Pop(); //Remove current total from last expression
total = result.Peek(); //Take previous total
Console.WriteLine("Running total:{0}", total);
}
This should get you most of the way there. They may be other things that you'll need to fix as well. I did test the undo and clear functionality and they seem to work as expected, but did not test anything else (other than basic + and - expressions).
I want to call an overload method using the value that was inserted into my texbox. By default it is of value string, so I have to check if it is of type int or double.
I am using the TryParse() to check and see if the values are of either int or double, but it causes me to have 2 variables for each textbox. I only want the 2 variables that has been successful.
I do not know how to determine which has been successful so that I can use them in the overload method call.
My code looks like this...
string a = textBox1.Text, b = textBox2.Text;
int f;
double d;
if(int.TryParse(a, out f))
{
}
else if(double.TryParse(a, out d))
{
}
int s;
double sD;
if (int.TryParse(b, out s))
{
}
else if(double.TryParse(b, out sD))
{
}
double x;
//Do not know which values to pass, because i only want the 2
//that was successful
Area(?, ?, out x);
label3.Text = "This is the value " + x;
}
private static void Area(int a, int b, out double x)
{
x = a * b;
}
private static void Area(double a, double b, out double x)
{
x = a * b;
}
private static void Area(int a, double b, out double x)
{
x = a * b;
}
If I then nest the if else statements, the compiler gives me an error saying that the double value is unassigned. I know a bunch of if else statements are ugly code, but it is the only way I currently know how.
if(f == '\0' && s == '\0')
{ Area(d, sD, out sum); }
else if(d=='\0' && s=='\0')
{Area(f, sD, out sum;)}
//and so on...
The simplest form i can come up with is putting the TryParses in sequence in a single if statement and, handling the first one that succeeds.
This leaves the possibility that one string cannot be parsed (or neither), so in that case i am throwing an exception
int intA;
int intB;
double doubleA;
double doubleB;
double x;
if(int.TryParse(a, out intA) && int.TryParse(b, out intB))
{
Area(intA, intB, out x);
}
else if (double.TryParse(a, out doubleA) && double.TryParse(b, out doubleB))
{
Area(doubleA, doubleB, out x);
}
else
{
throw new ArgumentException("cannot parse one or both numbers");
}
label3.Text = "This is the value " + x;
I made a custom method to print line and then read user input to assign it to double variable
here is my code :
double result = 0;
double a, b;
while (true)
{
if (Double.TryParse(GetValue("Enter value for a "), out a)
&& Double.TryParse(GetValue("Enter value for b "), out b))
{
result = a + b;
break;
}
else
{
Console.WriteLine("invalid value please try again..");
continue;
}
}
public static double GetValue(string input )
{
double z1;
double value;
Console.WriteLine(input);
value = Console.ReadLine();
z1 = value;
return z1;
}
but am facing an error which is that I can't convert 'double' to 'string'
. Can someone explain what am doing wrong ?
The problem is in the line
value = Console.ReadLine();
but you probably knew that already. ReadLine returns a string.
The easiest fix would be to return a string from GetValue, since you already try to parse it outside of the function:
public static string GetValue(string input )
{
Console.WriteLine(input);
return Console.ReadLine();
}
But an arguably cleaner solution would be to solve it in the function that asks the input and return a double from there:
double result;
double a, b;
a = GetValue("Enter value for a ");
b = GetValue("Enter value for b ");
result = a + b;
public static double GetValue(string input )
{
double value;
Console.WriteLine(input);
while (!Double.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("invalid value please try again..");
}
return value;
}
The reason I think this is slightly better, is because you isolate the logic of parsing into the function, so you need only one call to double.TryParse. Moreover, if someone would type an incorrect value for b, in your code they would need to start over with the value for a, where in my code, they just have to retry b.
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.