My code outputs the same string multiple times. For example, typing in 40 results in "Nope! Your answer is too high. Try again." twice, and it displays "your answer is too low" twice.
while (numberguess != 40.5)
{
numberguess = Console.Read();
if (numberguess < 40.5)
{
Console.WriteLine("Nope! Your answer is too low. Try again.");
}
else if (numberguess > 40.5)
{
Console.WriteLine("Nope! Your answer is too high. Try again.");
}
else if (numberguess == 40.5)
{
Console.WriteLine("Correct! Wow, I didn't really think you would figure it out!");
break;
}
}
I expect only one string to show up when typing in a number, and I want it to correspond to whether it is lower or higher than a particular number.
There are several problems with this single line:
numberguess = Console.Read();
First this returns an int, so it will never return 40.5. Also this reads one character at a time, including the ones input by the enter key, so when you type 40 and press Enter it reads '4', then '0' then '\r' and finally '\n' (converting those chars to int). That's why it displays four messages.
Instead you have to read everything typed before the Enter with Console.ReadLine() and then convert this (string) to a double. So in the end you have to do this:
numberguess = double.Parse(Console.ReadLine());
Console.Read() reads a single character as an int. If you're trying to get what the user typed before they hit enter, read the current line, and then parse an integer from it.
int.Parse(Console.ReadLine());
Related
I'm making a simple method where I'm going to use console input to pick a students number from a list, now for some reason the program crashes before I've pressed enter while reading the line and the VS tells me Input string was not in the correct format.
var whoisthestudent = Console.ReadLine();
int who = Convert.ToInt32(whoisthestudent);
So here's the part of the program that crashes, these are the first two lines of the method and when it crashes it gives me the format exception. I just can't figure out why it starts converting the readline before I've written anything or pressed enter?
Use int.TryParse to be on the safer side
Int studentId;
var whoisthestudent = Console.ReadLine();
If(int.TryParse(whoisthestudent, out studentId)
{
Console.WriteLine(studentId);
} else
{
Console.WriteLine("Failed to convert" );
}
I am fairly new to programming so have some mercy ;)
I am trying to build a program that can solve equations and give gradient and so on in c#, so I can make it more complex gradually. Problem is, there appears to be a wrong value from my input when I tried to start building it.
Console: Given value for "a":
9 The Output: 57
My Code:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input an linear Eqasion in the following Pattern -- a * x + b");
Console.Write("Given value for \"a\":");
decimal aValue;
aValue = Console.Read();
Console.Write(aValue);
}
}
}
Console.Read() returns an int, but not in the way you think. It returns the numeric value of the typed character, not the human-intuitive interpretation of a character that coincidentally happens to be a number. Consider for example what it would return if you type a letter, or any other non-numeric character.
And what is the numeric (decimal) value for the character '9'? 57 is.
It sounds like you want to read the line, not the character. For example:
string aValue;
aValue = Console.ReadLine();
Console.Write(aValue);
Remember that you'll need to press return to send the line to the application.
If you'll later need the value to be numeric, you'll still want to input the string but will want to parse it. For example:
string aValue;
aValue = Console.ReadLine();
if (decimal.TryParse(aValue, out decimal numericValue)
{
Console.Write(numericValue);
}
else
{
// The value could not be parsed as a decimal, handle this case as needed
}
Console.Read returns the character code entered on the command line in this scenario. The ASCII character code of 9 is 57. If you're wanting numeric input, you'd be better using Console.ReadLine with Decimal.Parse (or better yet, Decimal.TryParse)
It is also worth noting that Console.Read only returns one character at a time, meaning for any inputs past 1 digit you'll need special handling. I highly recommend using ReadLine and parsing the string over handling converting the character codes to the number they represent.
I have a snipped of code that I wrote that calculates how long the user has been alive. But the problem is, the program goes to hell if the user doesn't enter a integer e.g January or something else. I need to know how to stop this.
int inputYear, inputMonth, inputDay;
Console.WriteLine("Please enter the year you were born: ");
inputYear = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the Month you were born: ");
inputMonth = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the day you were born: ");
inputDay = int.Parse(Console.ReadLine());
DateTime myBrithdate = new DateTime(inputYear,inputMonth, inputDay);
TimeSpan myAge = DateTime.Now.Subtract(myBrithdate);
Console.WriteLine(myAge.TotalDays);
Console.ReadLine();
if the user doesn't enter a integer e.g January or something else
You can use Int32.TryParse method then..
Converts the string representation of a number in a specified style
and culture-specific format to its 32-bit signed integer equivalent. A
return value indicates whether the conversion succeeded.
Console.WriteLine("Please enter the Month you were born: ");
string s = Console.ReadLine();
int month;
if(Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out month))
{
// Your string input is valid to convert integer.
month = int.Parse(s);
}
else
{
// Your string input is invalid to convert integer.
}
Also TryParse method doesn't throw any exception and that's why you don't need to use any try-catch block with it.
This is far above my level, I have no idea what is going on here.
Ok. I try to explain a little bir more deep.
What you complain is the users input right? Beucase you said, you want to put int as an input. Not string like "January" or "May" etc..
When you read input with Console.ReadLine() method, it returns a string as a return type, not int. Doesn't matter user put as an input 3 or January, this method returns them as a string regardless what they are type is.
3 and January are strings in this case. But how we check these strings are actually convertable to an integer value? This is the part of why we using Int32.TryParse method. This method checks these inputs are convertable to integers or not so we can use this integer in DateTime constructor as a real integer.
This is because you are using int.Parse(Console.ReadLine()); - the int stands for integer. Well you could put a try catch block arround your code.
The original code would stand in the try block, because you want to try to run it- but if an error accours ( e.g. user types jan), the catch block handles the error and your program could go on without troubles.
I have another question about the TryParse method I have created to check for my user's input. Sorry for my extra question, but I ran into another complication and wanted more assistance on it, so I made another question since my last one is quite old. I was afraid no one would see this question if I post it on the last one.
There are no errors, but when I try to run it to test what my user's input, for everything I enter, including whole numbers, decimals, (1.00, 1.0, 1,000.0) it gives me the Messagebox.Show anyway. Here's what I created:
{
// Arrange the variables to the correct TextBox.
decimal Medical;
if (!decimal.TryParse(ChargeLabel.Text, out Medical))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Surgical;
if (!decimal.TryParse(ChargeLabel.Text, out Surgical))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Lab;
if (!decimal.TryParse(ChargeLabel.Text, out Lab))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Rehab;
if (!decimal.TryParse(ChargeLabel.Text, out Rehab))
{
MessageBox.Show("Please enter a decimal number.");
}
// Find the cost of Miscs by adding the Misc Costs together.
decimal MiscCharges = Medical + Surgical + Lab + Rehab;
ChargeLabel.Text = MiscCharges.ToString("c");
In other words, I try to input any form of numbers on the Medical, Surgical, Lab, and Rehab textboxes and it still gives me the same MessageBox. Will someone provide me help on how to let my application check my user's input correctly? Thanks you, and sorry again.
Make sure that you are entering numbers in a culture-correct format. Some cultures use comas as separators, others use dots. Try "123,4" and "123.4"
You are using the same label in each parsing statement.
decimal.TryParse(ChargeLabel.Text, out Medical)
decimal.TryParse(ChargeLabel.Text, out Surgical)
decimal.TryParse(ChargeLabel.Text, out Lab)
decimal.TryParse(ChargeLabel.Text, out Rehab)
EDIT I'd recommend putting a breakpoint in each MessageBox.Show line, then seeing what the string value you're parsing is.
You can also provide more information in the message shown:
decimal Rehab;
if (!decimal.TryParse(ChargeLabel.Text, out Rehab))
{
MessageBox.Show(string.Format("Unable to parse '{0}' as a decimal number.", ChargeLabel.Text));
}
I have some problem with a method that I have done in c#. I'm trying to stop user from entering anything else then y and n. It's almost working that I want, but user can still enter more than one sign, and then it doesn't work! How can I do to also check if char is more than one char? I thought the tryParse solved that? Thanks!
// Method to check if item is food or not
private void ReadIfFoodItem()
{
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
if(Char.IsNumber(responseFoodItem))
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
else
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
else
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
}
}
}
The following code "works" in that it produces the expected results.
char responseFoodItem;
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
Console.WriteLine("foodItem = true");
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
Console.WriteLine("foodItem = false");
}
else
{
Console.WriteLine("Unrecognised input");
}
}
else
{
Console.WriteLine("Invalid input");
}
However, has others have pointed out using ReadKey is a better solution if you want to limit the input to a single key. It also means that the user doesn't have to press the Return/Enter key for the input to be accepted.
char represents a single character, so How can I do to also check if char is more than one char? I thought the tryParse solved that? seems a bit nonsensical... TryParse will try and parse a single character from your input and will explicitly fail if the value is null or has a length > 1.
Instead of checking a character, just check the string, e.g.:
string line = Console.ReadLine();
switch (line.ToUpperInvariant())
{
case "Y":
// Do work for y/Y
break;
case "N":
// Do work for n/N
break;
default:
// Show error.
break;
}
char.TryParse simply tries to parse the string supplied as an argument, it does not limit the number of characters that you can input to the console using Console.ReadLine.
When the user inputs more than a single character, char.TryParse will fail because the string returned by Console.ReadLine doesn't contain a single character.
You should use Console.Read instead.
How can I do to also check if char is more than one char?
string line = Console.ReadLIne();
If(!string.IsNullOrEmpty(line) && line.Length > 1)
for reading a single char use Console.ReadChar() instead.
Console.ReadLine allows users to type a string of any length and press enter.
How can I do to also check if char is more than one char? I thought the tryParse solved that?
From the manual page:
Converts the value of the specified string to its equivalent Unicode character. A return code indicates whether the conversion succeeded or failed....The conversion fails if the s parameter is null or the length of s is not 1.
Have you tried using Console.ReadKey instead of ReadLine?
To check it the user has inserted more then one char you could check the string length instead of use Char.TryParse
......
private void ReadIfFoodItem()
{
string answer=string.empty;
Console.Write("Enter if food item or not (y/n): ");
answer=Console.ReadLine()
if (answer.lenght>=1))
{
//error
.......
}
...............
This answer should help you: How can I limit the number of characters for a console input? C#
The console does not limit the user input (well it does, but to 256 characters), nor does char.TryParse which doesn't do anything at all to limit the input length.
You can try using Console.ReadKey
It's just one keystroke for the user and you know there won't be more than one char.
Why not comparing to the input'ed string?
And why not simplifying the comparison?
using System.Linq;
private static string[] ValidAnswers = new string[]{ "y", "yes" };
// Method to check if item is food or not
private void ReadIfFoodItem() {
Console.Write("Enter if food item or not (y/n): ");
string ans = Console.ReadLine();
// Checks if the answer matches any of the valid ones, ignoring case.
if (PositiveAnswers.Any(a => string.Compare(a, ans, true) == 0)) {
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
} else {
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
}
Alternatively, as others said, you can use Console.ReadKey().
Use Console.ReadKey() to limit the amount of characters. To test whether you have a Y or an N then you can compare the ASCII codes or use a regular expression.