I need help with some of my code for a game calculator. So I wrote all this code, but the IF/THEN statement is acting weird.
Screenshot:
-
I typed in P and it should have gone to the ELSE part of the code, but instead it continued onto the if part. Please help!
{
class MainClass
{
public static void Main(string[] args) // IF YOU ARE TO REWRITE FROM MY SOURCE, ALL ORIGINAL CREDITORS MUST GO INTO THE CREDITS!
{
double num01;
double num02;
double num03;
double num04;
double num05;
double num06;
string CD = null;
string P = null;
string answer = null;
Console.Write("Diogenes's Calculator 1.0\n\nCredits: DoS (#57714)\n DZ(#54689)");
Console.WriteLine();
Console.WriteLine();
Console.Write("Hello! Would you like Charity Donation or Propaganda Calculator? (CD or P): ");
Console.ReadLine();
answer = Convert.ToString();
if(answer == CD) {
Console.WriteLine();
Console.Write("Howmuch influence does the target have?: ");
num01 = Convert.ToDouble(Console.ReadLine());
Console.Write("Howmuch is the cost of Charity Donatins? (Gold): ");
num02 = Convert.ToDouble(Console.ReadLine());
Console.Write("What % of influence does Charity Donation give (Made if value does change)?: ");
num03 = Convert.ToDouble(Console.ReadLine());
Console.Write(num02 + num03);
Console.ReadKey();
} else if(answer == P) {
answer = Convert.ToString();
Console.WriteLine();
Console.Write("Howmuch influence does the target have?: ");
num04 = Convert.ToDouble(Console.ReadLine());
Console.Write("Howmuch influence do you want the target to have?: ");
num05 = Convert.ToDouble(Console.ReadLine());
Console.Write("What % of influence does Propaganda take off (Made if value does change)?: ");
num06 = Convert.ToDouble(Console.ReadLine());
Console.Write(num04 + num05);
Console.ReadKey();
} else {
Console.WriteLine("Looks like you didn't type in CD or P. Buh Bye!");
Console.ReadKey();
}
}
}
}
you are checking if answer is equal to the value stored in the field P, not if answer is equal to the actual string "P". And P the variable is null.
Secondly, you are throwing away your user input here:
Console.ReadLine();
answer = Convert.ToString();
you are reading the console input into nothing, then assigning answer to the Convert object's string representation, which is probably a fully qualified namespace. You want:
answer = Console.ReadLine();
Console.Write("Hello! Would you like Charity Donation or Propaganda Calculator? (CD or P): ");
answer = Console.ReadLine();
if(answer == "CD") {
Related
I'm relatively new to programming and I'm working on various projects to get better at it. One is a calculator that I want to be able to solve more than just basic addition and subtraction. Currently, all I have is the basics with the quadratic formula. But my design weighs on user input to decide what to do. It prompts the user with "What would you like to do? Add: Sub: Div: Mul: Quad Equation:" After typic in "Add" the code operates normally but if I type in anything else like "Sub" or "Div". it does nothing. doesn't even spit back an error. As far as I can tell, my code is fine (well it's terrible code but it should work nonetheless) But I just do not know how to proceed.
using System;
namespace Better_Calculator
{
class Program
{
static void Main(string[] args)
{
double num01;
double num02;
double a;
double b;
double c;
System.Console.WriteLine("Welcome to how you are going to cheat through math lol");
System.Console.WriteLine("What would you like to do? \nAdd: \nSub: \nDiv: \nMul: \nQuad Equation: ");
if (Console.ReadLine() == "Add")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Add(num01, num02);
}
else if (System.Console.ReadLine() == "Sub")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Sub(num01, num02);
}
else if (System.Console.ReadLine() == "Mul")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Mul(num01, num02);
}
else if (System.Console.ReadLine() == "Div")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Div(num01, num02);
}
else if (System.Console.ReadLine() == "Quad Equation")
{
System.Console.WriteLine("what is a?");
a = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is b");
b = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is c");
c = Convert.ToInt32(Console.ReadLine());
Quad(a, b, c);
}
static void Add(double num01, double num02)
{
string answer = Convert.ToString(num01 + num02);
System.Console.WriteLine(answer);
}
static void Sub(double num01, double num02)
{
string answer = Convert.ToString(num01 - num02);
System.Console.WriteLine(answer);
}
static void Mul(double num01, double num02)
{
string answer = Convert.ToString(num01 * num02);
System.Console.WriteLine(answer);
}
static void Div(double num01, double num02)
{
string answer = Convert.ToString(num01 / num02);
System.Console.WriteLine(answer);
}
static void Quad(double a, double b, double c)
{
double bNeg = b * -1;
double bSqr = b * b;
double SqR = Math.Sqrt(bSqr - (4 * a * c));
double solvedAdd = (bNeg + SqR) / (2 * a);
double solvedSub = (bNeg - SqR) / (2 * a);
string answer = Convert.ToString(solvedAdd) + " or " + Convert.ToString(solvedSub);
System.Console.WriteLine(answer);
}
}
}
}
With every ´if´, you call Console.ReadLine() again, so if you enter "Quad Equation", your code has passed 5 Readlines until you reach the code that does Quad Equation.
Solution: Do only one Console.ReadLine() and put its result into a variable:
var userInput = Console.ReadLine();
and then, test against userInput in your if statements (ex.)e:
else if (userInput == "Sub")
You only need to do a ReadLine once and store the value, then use that to compare. For example:
var operation = Console.ReadLine();
if(operation == "Add")
{
// Do add stuff
}
But you should consider using a switch statement instead:
switch(operation)
{
case "Add":
// do Add Stuff
break;
case "Sub":
// do Add Stuff
break;
case "Mul":
// do Add Stuff
break;
// etc...
}
When we get input from console application from user may be they given as
CAPS, Small or combination of both
. In that situation you can use the following approach,
string value=Console.ReadLine();
if(string.Equals(value, "Add", StringComparison.CurrentCultureIgnoreCase))
{
// Do add stuff
}
else if(string.Equals(value, "Sub", StringComparison.CurrentCultureIgnoreCase))
{
// Do add stuff
}
I am switching from Python to C# and I am having trouble with the ReadLine() function. If I want to ask a user for input Python I did it like this:
x = int(input("Type any number: "))
In C# this becomes:
int x = Int32.Parse (Console.ReadLine());
But if I type this I get an error:
int x = Int32.Parse (Console.ReadLine("Type any number: "));
How do I ask the user to type something in C#?
You should change this:
int x = Int32.Parse (Console.ReadLine("Type any number: "));
to this:
Console.WriteLine("Type any number: "); // or Console.Write("Type any number: "); to enter number in the same line
int x = Int32.Parse(Console.ReadLine());
But if you enter some letter(or another symbol that cannot be parsed to int) you will get an Exception. To check if entered value is correct:
(Better option):
Console.WriteLine("Type any number: ");
int x;
if (int.TryParse(Console.ReadLine(), out x))
{
//correct input
}
else
{
//wrong input
}
Starting from C# 7 you can use inline variable declaration (out variables):
Console.WriteLine("Type any number: ");
if (int.TryParse(Console.ReadLine(), out var x)) // or out int x
{
//correct input
}
else
{
//wrong input
}
Console.WriteLine("Type any number");
string input = Console.ReadLine();
int x;
if (int.TryParse(input, out x))
{
//do your stuff here
}
else
{
Console.WriteLine("You didn't enter number");
}
Console.WriteLine("Type any number: ");
string str = Console.ReadLine();
Type a = Type.Parse(str);
where Type is Data Type you want to cast user input to.
I suggest reading few books on C# fundaments before turning to forums.
To be more generic I would suggest you to make an additional object ( because you cannot extend static objects in C# ) to behave like you've specified.
public static class ConsoleEx
{
public static T ReadLine<T>(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine();
return (T)Convert.ChangeType(input, typeof(T));
}
}
Of course you this code is not error free because it does not contains any constraints about the output type but still It will cast into some types without any problems.
For example. Using this code :
static void Main()
{
int result = ConsoleEx.ReadLine<int>("Type any number: ");
Console.WriteLine(result);
}
>>> Type any number:
<<< 1337
>>> 1337
Check this online
try this
Console.WriteLine("Type any number: ");
int x = Int32.Parse (Console.ReadLine());
I need some help making sure that when the user enters nothing, or not a number, it doesn't crash. I have it down so that it will tell them to enter a number if they don't, but I don't know how to make it go back to the original question and give them a chance to input correctly. Thanks for the help.
Console.WriteLine("How much is rent: ");
string strRent = Console.ReadLine();
double dblRent = 0.0;
if (double.TryParse(strRent, out dblRent))
{
Console.WriteLine("How much is the car payment: ");
string strCarPayment = Console.ReadLine();
double dblCarPayment = Convert.ToDouble(strCarPayment);
}
else
{
Console.WriteLine("Enter a number");
}
Console.WriteLine("How much is student loan payment: ");
string strStudentLoan = Console.ReadLine();
Console.WriteLine("How much is phone bill: ");
string strPhoneBill = Console.ReadLine();
Console.WriteLine("How much is electric bill: ");
string strElectricBill = Console.ReadLine();
Console.WriteLine("Fraction deposited: ");
string strFractionDeposited = Console.ReadLine();
Console.WriteLine("Amount leftover: ");
string strAmountLeft = Console.ReadLine();
double dblStudentLoan = Convert.ToDouble(strStudentLoan);
double dblPhoneBill = Convert.ToDouble(strPhoneBill);
double dblElectricBill = Convert.ToDouble(strElectricBill);
double dblFractionDeposited = Convert.ToDouble(strFractionDeposited);
double dblAmountLeft = Convert.ToDouble(strAmountLeft);
double dblBillSum = dblRent + dblCarPayment + dblStudentLoan + dblPhoneBill + dblElectricBill;
double afterBills = dblAmountLeft / (1 - dblFractionDeposited);
double totalPaycheck = afterBills + dblBillSum;
Console.WriteLine("Total Paycheck: " + totalPaycheck.ToString("C"));
Console.WriteLine("Enter wage $/hr: ");
string strWage = Console.ReadLine();
Console.WriteLine("Enter hours worked overtime: ");
string strHoursOT = Console.ReadLine();
Console.WriteLine("Enter overtime multiplier: ");
string strOTWage = Console.ReadLine();
double dblWage = Convert.ToDouble(strWage);
double dblHoursOT = Convert.ToDouble(strHoursOT);
double dblOTWage = Convert.ToDouble(strOTWage);
double OTPay = (dblWage * dblOTWage) * dblHoursOT;
Console.WriteLine("Overtime Pay: " + OTPay.ToString("C"));
Console.ReadLine();
}
}
}
You need a loop, something like this
Console.WriteLine("How much is rent: ");
string strRent = Console.ReadLine();
double dblRent = 0.0;
while (!double.TryParse(strRent, out dblRent))
{
Console.WriteLine("Enter a number");
strRent = Console.ReadLine();
}
Console.WriteLine("How much is the car payment: ");
string strCarPayment = Console.ReadLine();
double dblCarPayment = Convert.ToDouble(strCarPayment);
Try this
double dblRent = 0.0;
Boolean valid = false;
while (!valid)
{
if (double.TryParse(strRent, out dblRent))
{
Console.WriteLine("How much is the car payment: ");
string strCarPayment = Console.ReadLine();
double dblCarPayment = Convert.ToDouble(strCarPayment);
valid = true;
}
else
{
Console.WriteLine("Enter a number");
}
}
Since you are reading many doubles, you could create a method encapsulating reading and processing the number
private static double? ReadLineDouble()
{
while(true) {
string s = Console.ReadLine();
if (String.IsNullOrWhitespace(s)) {
return null; // The user wants to abort
}
double d;
if (Double.TryParse(s, out d)) {
return d;
}
Console.WriteLine("Please enter a valid number");
}
}
If the user just hits Enter probably he wants to abort. In this case the method returns null. This is possible, because the return type is a Nullable<double>. The shorthand notation for it is double?.
Now you can read a number like this:
double? rent = ReadLineDouble();
if (double == null) return; // Abort the program.
// Otherwise continue.
I am trying to create a program for a hotel where the user is to enter a character (either S, D, or L) and that is supposed to correspond with a code further down the line. I need help converting the user input (no matter what way they enter it) to be converted to uppercase so I can then use an if statement to do what I need to do.
My code so far is the following:
public static void Main()
{
int numdays;
double total = 0.0;
char roomtype, Continue;
Console.WriteLine("Welcome to checkout. We hope you enjoyed your stay!");
do
{
Console.Write("Please enter the number of days you stayed: ");
numdays = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("S = Single, D = Double, L = Luxery");
Console.Write("Please enter the type of room you stayed in: ");
roomtype = Convert.ToChar(Console.ReadLine());
**^Right Her is Where I Want To Convert To Uppercase^**
total = RoomCharge(numdays,roomtype);
Console.WriteLine("Thank you for staying at our motel. Your total is: {0}", total);
Console.Write("Do you want to process another payment? Y/N? : ");
Continue = Convert.ToChar(Console.ReadLine());
} while (Continue != 'N');
Console.WriteLine("Press any key to end");
Console.ReadKey();
}
public static double RoomCharge(int NumDays, char RoomType)
{
double Charge = 0;
if (RoomType =='S')
Charge = NumDays * 80.00;
if (RoomType =='D')
Charge= NumDays * 125.00;
if (RoomType =='L')
Charge = NumDays * 160.00;
Charge = Charge * (double)NumDays;
Charge = Charge * 1.13;
return Charge;
}
Try default ToUpper method.
roomtype = Char.ToUpper(roomtype);
Go through this http://msdn.microsoft.com/en-us/library/7d723h14%28v=vs.110%29.aspx
roomtype = Char.ToUpper(roomtype);
public static void Main()
{
int numdays;
double total = 0.0;
char roomtype, Continue;
Console.WriteLine("Welcome to checkout. We hope you enjoyed your stay!");
do
{
Console.Write("Please enter the number of days you stayed: ");
numdays = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("S = Single, D = Double, L = Luxery");
Console.Write("Please enter the type of room you stayed in: ");
roomtype = Convert.ToChar(Console.ReadLine());
roomtype = Char.ToUpper(roomtype);
total = RoomCharge(numdays,roomtype);
Console.WriteLine("Thank you for staying at our motel. Your total is: {0}", total);
Console.Write("Do you want to process another payment? Y/N? : ");
Continue = Convert.ToChar(Console.ReadLine());
} while (Continue != 'N');
Console.WriteLine("Press any key to end");
Console.ReadKey();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConTempConversion_LeeMichelle
{
class Program
{
static void Main(string[] args)
{
double fTemp;
double cTemp;
double convertC;
double convertF;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.WriteLine("3. Exit");
Console.Write("Enter choice: ");
Console.ReadKey();
int ichoice = 0;
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.ReadKey();
}
if (ichoice == 2)
{
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
convertF = ConvertFahrenheit(cTemp);
Console.WriteLine(cTemp + "Celsius is " + convertF + "Fahrenheit");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("____________________________________________________");
Console.ReadKey();
}
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
}
}
while (ichoice > 3);
Console.ReadKey();
}
static double ConvertCelcius(double c){
double f;
return f= 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f) {
double c;
return c = 5.0 / 9.0 * (f - 32);
}
}
}
so suppose the user has three options from 1 - 3. After option 3, there will be an error alert. my problem is why this code gives me an infinity loop? what did I do wrong? can I put break after each if statment?
Please help, thank you!
You're creating a do...while loop without anything to ever exit it. When the loop begins, ichoice is already set in stone. So you'll always be stuck in that loop!
You are never assigning a value to ichoice If I were you, I would try something like this:
int ichoice = 0;
int.TryParse(Console.ReadKey().ToString(), out ichoice );
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
int.TryParse(Console.ReadKey().ToString(), out ichoice );
Add the int.TryParse(Console.ReadKey().ToString(), out ichoice ); everywhere you have Console.Readline(). What this is doing is getting the user input and converting it to an integer (if it's not an integer, then the value is 0).
Also add this:
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
break;
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
int.TryParse(Console.ReadKey().ToString(), out ichoice );
}
Finally, remove this (I'm not quite sure what it was for...)
while (ichoice > 3);
Console.ReadKey();
When you need to do some prep work before your condition, the most straightforward way involves combining your loop with a separate structure.
This is the format to use when your loop condition is at the beginning of the loop:
prep work
while (condition) // if false then loop body will never run
{
loop body
}
This is the format to use when the loop condition is at the end of the loop:
prep work
do
{
loop body
}
while (condition); // loop body will always execute at least once
In this case, you have some prep work to do before each iteration--you want to get the key press from the user each time. For this, I recommend the following from Code Complete:
while (true) // loop termination condition is inside the loop
{
prep work
if (condition)
{
break;
}
loop body
}
In your case, it would look something like:
Console.Write("Enter choice: ");
while (true) // loop termination condition is inside the loop
{
Console.ReadKey();
if (ichoice == 3)
{
Console.WriteLine(...);
break;
}
...
}
Also, consider changing most of your ifs into else ifs; otherwise, you're repeatedly checking the condition even when you've gone through one case.
you should assign a value to iChoice. and set your while to read a terminating character. like:
namespace YourNameSpace
{
static void Main(string[] args)
{
double fTemp;
double cTemp;
double convertC;
double convertF;
int iChoice;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.Write("Enter choice(0 to exit): ");
iChoice = Console.Read();
do{
switch(iChoice)
{
case 1:
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
case 2:
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
convertF = ConvertFahrenheit(cTemp);
Console.WriteLine(cTemp + "Celsius is " + convertF + "Fahrenheit");
}
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.Write("Enter choice(0 to exit): ");
iChoice = Console.Read();
}while(iChoice != 0);
}
static double ConvertCelcius(double c){
double f;
return f= 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f) {
double c;
return c = 5.0 / 9.0 * (f - 32);
}
}
Each time you call Console.ReadKey you should store returning value.You are receiving input from user but you didn't store it anywhere.
First you can create a function to get ichoice, and force user to enter the correct value:
static void GetChoice(ref int ichoice)
{
string input = Console.ReadLine();
Console.Write("Enter choice: ");
bool result = int.TryParse(input, out ichoice);
if (!result)
{
while (!result && ichoice > 3)
{
Console.WriteLine("Invalid value.Try again:");
input = Console.ReadLine();
result = int.TryParse(input, out ichoice);
}
}
}
Then use this function whenever you need to make a choice.
Here is the working version or your program:
double fTemp;
double cTemp;
double convertC;
double convertF;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.WriteLine("3. Exit");
int ichoice = 0;
GetChoice(ref ichoice);
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
GetChoice(ref ichoice);
}
if (ichoice == 2)
{
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
Console.WriteLine(cTemp + "Celsius is " + cTemp + "Fahrenheit");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("____________________________________________________");
GetChoice(ref ichoice);
}
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
}
}
while (ichoice < 3);
}
static double ConvertCelcius(double c)
{
double f;
return f = 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f)
{
double c;
return c = 5.0 / 9.0 * (f - 32);
}
And here is the full code: http://pastebin.com/bkegSAFL