C# Double values not printing - c#

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}");

Related

How do you use a "char" as a sentinel value in a while loop

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
}

Switch jumping to default case [duplicate]

This question already has answers here:
Difference between Console.Read() and Console.ReadLine()?
(12 answers)
Closed 1 year ago.
I don't get why my integer isn't coming out correctly, Console.Read() method says it's returning an integer, why isn't WriteLine displaying it correctly?
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ dimension);
Console.Read() only returns the first character of what was typed. You should be using Console.ReadLine():
Example:
int suppliedInt;
Console.WriteLine("Please enter a number greater than zero");
Int32.TryParse(Console.ReadLine(), out suppliedInt);
if (suppliedInt > 0) {
Console.WriteLine("You entered: " + suppliedInt);
}
else {
Console.WriteLine("You entered an invalid number. Press any key to exit");
}
Console.ReadLine();
Additional Resources:
MSDN - Console.Read()
MSDN - Console.ReadLine()
From the MSDN:
Return Value
Type: System.Int32 The next character from the input stream, or
negative one (-1) if there are currently no more characters to be
read.
Your program is returning but you're not seeing, would you please see below code block:
You are not be able to see the output if the output window doesn't stay.
int dimension;
dimension = Console.Read();
Console.WriteLine("" + dimension);
Console.ReadLine();
Console.Read() returns ASCII code of first symbol in input. You can do
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ (char)dimension);
and you'll see right first symbol in input, as
(char)dimension
will give you symbol by it's ASCII code.
int a = 0;
if(Int32.TryParse(Console.ReadLine(), out a))
{
// Do your calculations with 'a'
}
else
{
// Some warnings
}
The Console.Read method returns only a single character wrapped in an int, so that is only applicable if you are reading a number that is only one digit long, otherwise you'll always get only the first digit.
Since the return value of Read is actually a character, you cannot use it directly as an integer, you would need to parse it from character to integer.
But assuming that you want a number that is longer than one digit, then you really need to use Console.ReadLine instead and convert the input to an integer using int.TryParse. If int.TryParse returns false you can warn the user that he provided an invalid input and ask for the dimension again.
Sample code:
int dimension;
bool isValidDimension;
do
{
Console.Write("Dimension: ");
string input = Console.ReadLine();
isValidDimension = int.TryParse(input, out dimension);
if (!isValidDimension)
{
Console.WriteLine("Invalid dimension... please try again.");
Console.WriteLine();
}
} while (!isValidDimension);
you should it as follow
static void Main()
{
int Number;
string strNumber;
strNumber = Console.ReadLine();
Number = int.Parse(strNumber);
Console.WriteLine("" + dimension);
}

C# code executes even when variable not assigned

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();
}

How to check for a double type response in an if statement

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.
// ...
}

Console.Read not returning my int32 [duplicate]

This question already has answers here:
Difference between Console.Read() and Console.ReadLine()?
(12 answers)
Closed 1 year ago.
I don't get why my integer isn't coming out correctly, Console.Read() method says it's returning an integer, why isn't WriteLine displaying it correctly?
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ dimension);
Console.Read() only returns the first character of what was typed. You should be using Console.ReadLine():
Example:
int suppliedInt;
Console.WriteLine("Please enter a number greater than zero");
Int32.TryParse(Console.ReadLine(), out suppliedInt);
if (suppliedInt > 0) {
Console.WriteLine("You entered: " + suppliedInt);
}
else {
Console.WriteLine("You entered an invalid number. Press any key to exit");
}
Console.ReadLine();
Additional Resources:
MSDN - Console.Read()
MSDN - Console.ReadLine()
From the MSDN:
Return Value
Type: System.Int32 The next character from the input stream, or
negative one (-1) if there are currently no more characters to be
read.
Your program is returning but you're not seeing, would you please see below code block:
You are not be able to see the output if the output window doesn't stay.
int dimension;
dimension = Console.Read();
Console.WriteLine("" + dimension);
Console.ReadLine();
Console.Read() returns ASCII code of first symbol in input. You can do
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ (char)dimension);
and you'll see right first symbol in input, as
(char)dimension
will give you symbol by it's ASCII code.
int a = 0;
if(Int32.TryParse(Console.ReadLine(), out a))
{
// Do your calculations with 'a'
}
else
{
// Some warnings
}
The Console.Read method returns only a single character wrapped in an int, so that is only applicable if you are reading a number that is only one digit long, otherwise you'll always get only the first digit.
Since the return value of Read is actually a character, you cannot use it directly as an integer, you would need to parse it from character to integer.
But assuming that you want a number that is longer than one digit, then you really need to use Console.ReadLine instead and convert the input to an integer using int.TryParse. If int.TryParse returns false you can warn the user that he provided an invalid input and ask for the dimension again.
Sample code:
int dimension;
bool isValidDimension;
do
{
Console.Write("Dimension: ");
string input = Console.ReadLine();
isValidDimension = int.TryParse(input, out dimension);
if (!isValidDimension)
{
Console.WriteLine("Invalid dimension... please try again.");
Console.WriteLine();
}
} while (!isValidDimension);
you should it as follow
static void Main()
{
int Number;
string strNumber;
strNumber = Console.ReadLine();
Number = int.Parse(strNumber);
Console.WriteLine("" + dimension);
}

Categories