As you can probably tell from my question, I am very new to coding. I am trying to make a calculator that computes some formulas that are used in physics. However, the code runs the formula before the user has time to enter a value for A, in this example at least. Here is the example:
case "f = ma":
Console.WriteLine("Type the value for M in KG:");
var FM = Console.Read();
Console.WriteLine("Type the value for A in M/S:");
var FA = Console.Read();
var FMARes = FM * FA;
Console.WriteLine("Your answer (in Newtowns) is " + FMARes);
break;
How am I able to check whether a value has been assigned to the variable A, and only run the formula after the variable has an assigned value? Thanks.
You need to use ReadLine instead of Read. You also need to do another ReadLine at the bottom so the user can see the result. And...you should validate that the user entered a valid number. This could be refactored a bit to avoid duplicate code - etc. - but see if this works for you! Good luck!!
static void Main(string[] args)
{
double fm;
double fa;
// Use ReadLine instead of Read
Console.WriteLine("Type the value for M in KG:");
var input = Console.ReadLine();
// Now you need to cast it to a double -
// -- but only if the user entered a valid number
if (!double.TryParse(input, out fm))
{
Console.WriteLine("Please enter a valid number for M");
Console.ReadLine();
return;
}
Console.WriteLine("Type the value for A in M/S:");
input = Console.ReadLine();
if (!double.TryParse(input, out fa))
{
Console.WriteLine("Please enter a valid number for A");
Console.ReadLine();
return;
}
// Now we have valid values for fa and fm
// It's a better programming practice to use the string format
// intead of + here...
Console.WriteLine($"Your answer (in Newtowns) is {fm * fa}");
// You need another read here or the program will just exit
Console.WriteLine("Press Enter to end the program");
Console.ReadLine();
}
Related
Having some problems with my Console Calculator
I want to prohibit user inputing a words instead of numbers.
I wrote this code and its converting words to zero but i want user to type a number instead of words. And if user still typing words program should ask user to type number.
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("----------------------");
Console.WriteLine("------Calculator------");
Console.WriteLine("----------------------");
do
{
double num1 = 0;
double num2 = 0;
double result = 0;
bool result0;
Console.WriteLine("Enter number one: ");
try
{
double.TryParse(Console.ReadLine(), out num1);
if ()
{
Console.WriteLine("Incorrect number!\nType another number:");
num1 = Convert.ToDouble(Console.ReadLine());
}
}
catch (Exception e)
{
}
Console.WriteLine("Enter number two: ");
num2 = Convert.ToDouble(Console.ReadLine());
You have to use double.TryParse() inside a if condition with negation operator.
If you want to force user to show "Incorrect number!\nType another number:" message till the user enters correct integer, use while() loop instead of if() condition.
while (!double.TryParse(Console.ReadLine(), out num1))
Console.WriteLine("Incorrect number!\nType another number:");
Why we should use double.TryParse() inside if condition?
double.TryParse(), parse string value to double and return true if conversion succeeded or not.
In your case, if user enters word instead of number then conversion will fail and use of !(negation) will iterate the loop again.
My Instructions:
Implement a C# console application/program that makes use of a sentinel controlled while-loop structure to continuously prompt, read and store the test results entered by the user. The user will stop his/her input sequence by entering a ‘x’ character. You also need to make use of a switch selection structure (nested inside of the while loop).
e.g code to be used:
char stop = 'x';
Console.WriteLine("Enter result (x to stop): ");
results = Convert.ToChar(Console.ReadLine());
while(results != stop)
{
Console.WriteLine("Enter result (x to stop): ");
results = Convert.ToChar(Console.ReadLine());
}
When I try to enter the 'x' as is, it does not work
you are using Console.WriteLine, but you should use Console.ReadKey and omit Convert.ToChar instead get the KeyChar property of the returned value.
so
while(results != stop)
{
Console.WriteLine("Enter result (x to stop): ");
results = Console.ReadKey().KeyChar;
}
should work, I didn't test it
You convert into wrong type: not every string can be converted into a single char (say, "xenogg").
However, every char can be represented as a string with a help of ToString():
char stop = 'x';
// Keep looping ...
while (true) {
// ...and asking user for input...
Console.WriteLine("Enter result (x to stop): ");
string results = Console.ReadLine();
// ... until (s)he puts "x"
// put StringComparison.OrdinalIgnoreCase if 'X' is exit as well as 'x'
if (string.Equals(results.Trim(), x.ToString(), StringComparison.Ordinal))
break;
// results is not "x"
//TODO: add relevant code here
}
Okay so my program is supposed to take values that the user gives and then performs a calculation with them and then returns them, the problem is that when I try to write a Console.WriteLine to print the values, nothing appears where the variable should and I have no idea what I'm doing wrong
double HumanStrideLength = 0;
double HumanHeight;
double HumanVelocity;
double HumanStrideFrequency = 0;
string Answer;
string AnimalName;
double AnimalLength;
double AnimalStrideLength;
Console.WriteLine("Hello and welcome to Animal Run");
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
Console.WriteLine("Do you know your stride length?");
Answer = Console.ReadLine();
if ((Answer == "Yes") || (Answer == "yes") || (Answer == "y") || (Answer == "Y") || (Answer == "Yeah") || (Answer == "yeah"))
{
Console.WriteLine("Please input your stride length in CM");
try
{
HumanStrideLength = double.Parse(Console.ReadLine());
}
catch(FormatException f)
{
Console.WriteLine(f.Message);
}
}
else
{
Console.WriteLine("What is your height in CM");
HumanHeight = Double.Parse(Console.ReadLine());
HumanStrideLength = HumanHeight * 0.413;
}
Console.WriteLine("test", HumanStrideLength);
So here where it is supposed to print the variable HumanStrideLength it instead prints just the word "test".
If you call Console.WriteLine() with multiple arguments, the first argument must be a format string. This means that it has to contain something like {0}, which is a placeholder that will be replaced by the additional arguments to Console.WriteLine(). For example, change:
Console.WriteLine("test", HumanStrideLength);
to
Console.WriteLine("test {0}", HumanStrideLength);
And the output you should see if HumanStrideLength is 12.3, for example, will be:
test 12.3
or
test 12.3000001
due to floating point inaccuracy.
You can include multiple placeholders like this, with the number inside of each one corresponding to the zero-based index of the parameter that it will be replaced with:
Console.WriteLine("testing {0}, {1}", 2.3, 4.5);
will write "testing 2.3, 4.5" to the console. See documentation on MSDN for more information on this.
If you want to be more concise, you can also just use string interpolation instead of a format string. This feature was introduced in C# 6:
Console.WriteLine($"test {HumanStrideLength}");
I'm trying to check if the user's response is a double or an int, but the int is specific, whereas the double is not, as I probably made a right mess of explaining it, here's the code:
Console.WriteLine("\n 2) Q: How old is Sally? \n");
int nSallyAge = Convert.ToInt32(Console.ReadLine());
double dSallyAge = Convert.ToDouble((nSallyAge));
if (nSallyAge == 62 || dSallyAge == 62.0)
{
// Increase Score
sUser1Score++;
Console.WriteLine("\n A: Correct, Sally's age is 62, you have been awarded 1 point. \n");
Console.ReadLine();
}
What I'm trying to do, is instead of dSallyAge HAS to equal 62.0, it just has to equal any double figure.
I would approach this problem by first creating a method that gets a double from the user (that will, of course, also accept an int). This removes error handling from your main code.
NOTE in the code below, Math.Truncate can be replaced by Math.Floor, with the same result:
private static double GetDoubleFromUser(string prompt)
{
double input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (double.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again.");
}
return input;
}
Then, in my main code, I would get the number from the user, and use the Math.Truncate method to just read the first part of the double passed in by the user (this is what it sounds like you want to do). This means that if the user enters anything from 62 to 62.0 to 62.999, it will truncate the result to '62':
double nSallyAge = GetDoubleFromUser("2) Q: How old is Sally? ");
if (Math.Truncate(nSallyAge) == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Other alternative ways to use this are:
int sallyAge = Math.Truncate(GetDoubleFromUser("2) Q: How old is Sally? "));
if (sallyAge == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Or, you could use an input function that returns an int in the first place:
private static int GetIntFromUser(string prompt)
{
return Math.Truncate(GetDoubleFromUser(prompt));
}
In your code above, you are converting the input to an integer and then converting the int result to a double.
Assuming that you are only allowing numerical values to be entered, why not try something like this. This will identify if the input contained decimals or not:
string input = Console.ReadLine();
int iSallyAge;
double dSallyAge;
if (!Int32.TryParse(input, iSallyAge))
{
dSallyAge = Double.Parse(input);
}
You should be using Double.TryParse to parse the user input to a double and then test that value to see whether it's equal to 62.0.
double age;
if (double.TryParse(Console.ReadLine(), out age) && age == 62.0)
{
// age is 62.
// ...
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written up to this place and am stuck I need help on how to terminate a program or continue .
What I mean is that when I ask the question would you like to withdraw today and if their response is NO then the program should terminate but if its YES it should continue.
What am I missing?
Please implement the aspect where by the program should terminate using the N for NO statement i didn't received the answer to that.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
Console.ReadLine();
}
}
}
You are on the right track. What you are missing is to take and evaluate the user input - this is the information returned by the Console.ReadLine method (as mentioned in the comments) like this:
line = Console.ReadLine();
Your code could look like this:
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// save user input
var userInput = Console.ReadLine();
// evaluate if user wants to continue or not
if (userInput.ToLower() == "y")
{
// if yes, go further
Console.WriteLine("continue with other action...");
}
// else bye
Console.WriteLine("goodbye");
The line for the PIN already uses the user input! The same can be done with the question. If you want to stay in the loop until the user does not want to withdraw any more, than you need more than if-else. Take a look at the iteration statements like do and while.
A solution could look like this:
// user input = y or n
string choice;
// user pin
int pin = 0;
// state that indicates if the user wants to continue or not
bool continueLoop = false;
do
{
// greet user
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// take input
choice = Console.ReadLine();
// check if user has entered valid input
if (choice.ToLower() == "y" || choice.ToLower() == "n")
{
// default decision is "user does not want to continue" = exit
continueLoop = false;
// user has choosen to continue
if (choice.ToLower() == "y")
{
// user wants to do something, so stay in the loop
continueLoop = true;
// ask for pin
Console.WriteLine("Enter your pin");
var pinAsText = Console.ReadLine();
// convert the pin to number: if (int.TryParse(pinAsText, out pin)) ...
if (pinAsText == "1234")
{
Console.WriteLine("PIN correct");
// continue with logic here, for example take amount
}
else
{
Console.WriteLine("PIN incorrect");
}
}
}
else
{
Console.WriteLine("Please enter Y or N");
continueLoop = true;
}
} while (continueLoop);
Console.WriteLine("goodbye");
Now the flow looks like this:
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 3
PIN incorrect
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 1234
PIN correct
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> N
goodbye
Certainly when your users have two different choice , you should use if in your program . Also you should save user's answer into a local variable to process it .
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
char answer = char.Parse(Console.ReadLine());
if (answer == 'Y')
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
}
When you write nothing for "no" , your program will terminate .
Also you can use string instead of char :
string answer = Console.ReadLine();
if (answer == "Y")
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
By the way, there are a lot of possible errors in your code (e.g. enter a character instead of integer for variable ' pin ') that must be handled by try-catch.