Error happening when no value - c#

I created a program that requires the user to input a value into a text box. I'm trying to have the text box default to 0 if there is no value put in by the user.
Currently, if there is no value put in and the calculation is attempted I get the error "input string was not in a correct format" error.
This is what I have:
cexp = int.Parse(currentexp.Text);
currentexp.Text = "";
I want to try to do something like this:
if (currentexp.text == "")
set cexp = 0
So if the text box is empty then I want to set the variable cexp to equal 0.

Solution 1 : You can use Conditional operator for setting the default value.
int cexp=(!String.IsNullOrWhiteSpace(currentexp.Text)) ? Convert.ToInt32(currentexp.text) : 0;
Solution 2: You can use int.TryParse() to perform the validation.
int cexp;
if(int.TryParse(currentexp.Text,out cexp))
{
//conversion successfull do some thing here
}
else
{
//conversion failed so do something here
}

You can use LINQ and conditional operator:
cexp = !currentexp.Text.All(char.IsDigit) ||
!currentexp.Text.Any() ? 0 : int.Parse(currentexp.Text)
This will set cexp to zero when currentexp.Text contains one or more non-digit characters.

It might be good to use int.TryParse for this, since the user is entering in data.
int cexp = 0;
if (!int.TryParse(textBox1.Text, out cexp))
{
var result = MessageBox.Show("An invalid entry was entered, do you want to use 0 instead?",
"Invalid Entry", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
//do stuff to continue here
//cexp will already be 0
}
else
{
//don't continue, they wanted to try again
}
}
This will default the value of cexp to 0, and if the user enters something invalid it will warn them (and still keep cexp at 0). If they put in a correct value, then cexp will be updated to what the user entered.
If you don't want to warn the user or anything, and just want to continue, this will work.
int cexp = 0; //default to 0
int.TryParse(currentexptextBox1.Text, out cexp); //try to get a number, if it fails, cexp will still be 0

Related

convert string to int error in c#

Hello I am trying to convert String to Integer.
The code below shows a part from where I am trying to convert my string to integer.
if (other.gameObject.CompareTag("PickUp"))
{
if ( checkpointboolean == false)
{
string pickupName = other.ToString(); //other = Pickup4
//Remove first 6 letters thus remaining with '4'
string y = pickupName.Substring(6);
print(y); // 4 is being printed
int x = 0;
int.TryParse(y, out x);
print (x); // 0 is being printed
I also tried the below code and instead of '0' I am getting the following error:
if (other.gameObject.CompareTag("PickUp"))
{
if ( checkpointboolean == false)
{
//Get Object name ex: Pickup4
string pickupName = other.ToString();
//Remove first 6 letters thus remaining with '4'
string y = pickupName.Substring(6);
print(y);
int x = int.Parse(y);
FormatException: Input string was not in the correct format
System.Int32.Parse (System.String s)
int.TryParse returns a boolean, true if it succeeded and false if not. You need to wrap this in a if block and do something with that logic.
if(int.TryParse(y, out x))
print (x); // y was able to be converted to an int
else
// inform the caller that y was not numeric, your conversion to number failed
As far as why your number is not converted I could not say until you post what the string value is.
Your first attempt is the best for this case, that code works fine, The int.TryParse() giving 0 to the out parameter and returns false means the conversion is failed. The input string is not in the correct format/ it cannot be converted to an integer. You can check this by using the return value of the int.TryParse(). For this what you need to do is :-
if(int.TryParse(y, out x))
print (x); //
else
print ("Invalid input - Conversion failed");
First of all, ToString() usually uses for debug purpose so there's no guarantee that
other.ToString()
will return the expected "Pickup4" in the next version of the software. You, probably, want something like
int x = other.gameObject.SomeProperty;
int x = other.SomeOtherProperty;
int x = other.ComputePickUp();
...
If you, however, insist on .ToString() you'd rather not hardcode six letters (the reason is the same: debug information tends to change from version to version), but use regular expressions or something:
var match = Regex.Match(other.ToString(), "-?[0-9]+");
if (match.Success) {
int value;
if (int.TryParse(match.Value, out value))
print(value);
else
print(match.Value + " is not an integer value");
}
else
print("Unexpected value: " + other.ToString());

c# try and catch/ error handling

I am currently working on a program and I am finalising it by going over with error handling. I have several cases which look like:
int stockbankInput = Convert.ToInt32(Console.ReadLine());
Here, the user must enter either 1, 2, 3. I have tried to use an if statement to catch the error if anybody inputs a blankspace/string/character or a number that is not 1,2 or 3 but it doesn't work in the same sense as a string input. Below is what I have tried:
if(stockbankInput == null)
{
Console.WriteLine("Error: Please enter either 1, 2 or 3");
stockbankInput = 0;
goto menuRestartLine;
}
However, you cannot link 'null' with an integer input, only a string. Can anybody help with this please?
Use the Int32 TryParse method:
int input;
var successful = Int32.TryParse(Console.ReadLine(), out input);
if (!successful)
// do something else
else
return input;
You're checking if an int is null, which will always return false because an int cannot be null.
You can use 'int?' (Nullable int) but Convert.ToInt32 will not return null. If the value of the int cannot be resolved it will resolve to the default value of zero. You can either check if the returned int is zero or do some further checking of the returned string:
int input = 0;
string errorMessage = "Error: Please enter either 1, 2 or 3";
while(true)
{
try
{
input = Convert.ToInt32(Console.ReadLine());
if (input == 0 || input > 3)
{
Console.WriteLine(errorMessage);
}
else
{
break;
}
}
catch(FormatException)
{
Console.WriteLine(errorMessage);
}
}
With this you your returned value "int input" will either be 0 or the number you entered and FormatExceptions caused by the string to convert containing symbols other than the digits 0-9 will be caught in the try/catch statement.
give this sample program a try:
static void Main(string[] args)
{
int stockbankInput = 0;
bool firstTry = true;
while(stockbankInput < 1 | stockbankInput > 3)
{
if(!firstTry)
Console.WriteLine("Error: Please enter either 1, 2 or 3");
firstTry = false;
Int32.TryParse(Console.ReadLine(), out stockbankInput);
}
}
First of all, don't use goto statements. They are considered bad practice, and it's like a blinding red light when reading your question - that's all I can focus on.
As per your question, an int or Int32 cannot be null. So you can't compare it to null. Give it a default value, and then check that.
This is a scenario where you don't need to check for an error, but just need to validate input. Use TryParse, which will set your out parameter if the parse is successful, or else set it to 0.
Next, you want to loop until you are given good input. An if statement is executed once, a loop will guarantee that when you leave it, your input will be valid.
Lastly, the firstTry is just a nice way to let the user know, after their first try, that they screwed up.

How to validate a null input

the problem I'm having is to validate the input means putting it in a try catch which then wont pass the variable through and I'm getting this error:
Use of unassigned local variable 'MainMenuSelection'
I've validated using this method before but for some reason it's not working now, please help
//Take the menu selection
try
{
mainMenuSelection = byte.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a valid selection");
}
switch (mainMenuSelection) //Where error is shown
Obviously user can input anything which would not be parsed as a single byte. Try out using Byte.TryParse() method which does not generate exception and just return status flag.
You can go further and add more analysis for an user input if needed:
// Initialize by a default value to avoid
// "Use of unassigned local variable 'MainMenuSelection'" error
byte mainMenuSelection = 0x00;
string input = Console.ReadLine();
// If acceptable - remove possible spaces at the start and the end of a string
input = input.Trim();
if (input.Lenght > 1)
{
// can you do anything if user entered multiple characters?
}
else
{
if (!byte.TryParse(input, out mainMenuSelection))
{
// parsing error
}
else
{
// ok, do switch
}
}
Also perhaps you just need a single character not a byte?
Then just do:
// Character with code 0x00 would be a default value.
// and indicate that nothing was read/parsed
string input = Console.ReadLine();
char mainMenuSelection = input.Length > 0 ? input[0] : 0x00;
A better method would be to use byte.TryParse(). It's made specifically for these types of scenarios.
byte b;
if (byte.TryParse("1", out b))
{
//do something with b
}
else
{
//can't be parsed
}
If you're just concerned about the input itself, you can use the Byte.TryParse Method and then handle the false boolean case instead.
byte mainMenuSelection;
if (Byte.TryParse(Console.ReadLine(), out mainMenuSelection)
{
switch(mainMenuSelection);
}
else
{
Console.WriteLine("Please enter a valid selection");
}

What is the correct way to limit the range of values a property will accept?

I have a user control with some public properties. A particular property is an integer, but must only accept positive values that are less than a const max value. At present I do the following:
private int markerwidth = 2;
[DefaultValue(2), Category("Appearance"), Description("Size of position marker")]
public int MarkerWidth
{
get
{
return this.markerwidth;
}
set
{
if (value > 0 && value <= MAXMARKERWIDTH)
{
this.markerwidth = value;
}
}
}
This does the job, but fails silently. I guess I could add logic to use 0 for negative values and the max value for those that exceed it, but it's still not ideal.
By way of contrast, the TabValue property (inherited from UserControl) complains if I try to set a negative value at design time (and presumably at run time).
If this achieved with a normal exception? Or is there a better way? An attribute maybe?
The most optimal way is to achieve via exception. Just continue your code
if (value > 0 && value <= MAXMARKERWIDTH)
{
this.markerwidth = value;
}
else
{
throw new ArgumentOutOfRangeException("Invalid value. Value must be between 0 and " + MAXMARKERWIDTH.ToString());
}
EDIT
Yes, Wiktor Zychla is absolutely right! I corrected the answer.
There is a builtin ArgumentOutOfRangeException, I guess it fits here.

C# Input string was not in a correct format

Working on parsing from a text box to int to get into the incrementHour method as shown.
if (txtHourPlus.Text != String.Empty)
{
time1.incrementHour(int.Parse(txtHour.Text));
}
And in the time class: (the time1 objects class)
public int incrementHour(int step)
{
if (step > 0 && hour < 24)
{
//step = step % hour;
hour = (hour + step) % 24;
time.AddHours(hour);
return hour;
}//end of if
else
{
MessageBox.Show("Please enter a positive number.");
return 0;
}//end of else
}//end of incrementHour
not sure why i'm getting this error. I'm converting it to the corrent data type. Because it accepts an int variable.
Alright well i got it to take the value (small mistake >.> Don't even wanna say it)
However as someone already said the method probably needs work because i'm trying to change the Datetime value that i get in the first place and add an hour or subtract and etc etc.
That will happen if someone has typed "foo" into the text box, for example. You should use int.TryParse instead, which lets you detect the error without an exception being thrown.
I notice that you're not actually using the return value of your method though - just like you're not using the return value of time.AddHours. You are aware that DateTime.AddHours doesn't actually modify the value you're calling it on, aren't you? (I suspect you'll need to tweak that method quite a bit, actually... there are various potential problems with it, depending on exact what you're trying to do.)
(Finally, I'd change the method name to IncrementHour to comply with .NET conventions.)
you are testing txtHourPlus for emptiness, but then parsing and passing txtHour. typo (?)
If your input isn't parsable as an integer, attempting to parse it will raise an exception. Validate or use Int32.TryParse()
Change this part of your code:
if (txtHour.Text != String.Empty)
{
int parsedValue;
if (int.TryParse(txtHour.Text, out parsedValue))
{
time1.incrementHour(parsedValue);
}
else
{
// non-numeric value was entered into the textbox - handle accordingly.
}
}

Categories