Input string was not in correct form - c#

Im really bad with c# i have only really the basic knowladge of c# i have this piece of code but i cant get it to work probelly debugger says the problem is here http://puu.sh/2h2wV the code is here this is im sorry this is probally such an easy mistake
i had other code true,was my old programm :(
Console.WriteLine("Sisesta esimene arv vahemikus 10-20");
vastus1 = int.Parse(Console.ReadLine());
Console.WriteLine("sisesta teine arv vahemikus 20-32");
vastus2 = int.Parse(Console.ReadLine());
Console.WriteLine("Vastus {0}", vastus2 - vastus1);
string tekst1 = Console.ReadLine();
vastus3 = int.Parse(tekst1); <------ debugger says problem is here
}
while ((vastus1 < 1 || vastus2 < 12));
if (vastus3 >= 3 && vastus3 >= 5)
{
Console.WriteLine("On Kevad");
{
if (vastus3 >= 6 && vastus3 >= 8)
{
Console.WriteLine("on suvi");
}
}
if (vastus3 >= 9 && vastus3 >= 11)
{
Console.WriteLine("on sügis");
}
if (vastus3 >= 11 && vastus3 >= 2)
{
Console.WriteLine("on talv");
}
}
}
}
}

Well the error says it all really
The input string was not in the right format
In the context of what you're doing, this means that whatever you've typed into the console which you're passing directly to int.Parse cannot be parsed as an int.
If you expect that sometimes what is typed in to the console to not be numeric you could use int.TryParse to ascertain whether it is valid.
int vastus3 = 0;
while(!int.TryParse(Console.ReadLine(),out vastus3 ))
{
Console.WriteLine("Invalid number, try again!");
}
// here "vastus3" will have your integer
This can go into your code exactly where your current line which fails is.

Jamiec's explanation is correct. If the integers you are looking for always occur in the same format at the end of the string you could use Substring to get the specific characters then do your comparison checks.
Here is an example on how to remove characters from the end of a string using Substring.
Substring a string from the end of the string
And the msdn
http://msdn.microsoft.com/en-us/library/system.string.substring%28v=vs.71%29.aspx

Related

How do I check that even positions of a string array have only numbers?

I am learning my first ever programming language - which is C#.
I am making my first project in my apprenticeship which is teaching me C#. It is to produce a basic calculator.
The basic calculator takes a string input and provides a result. For example, input: "5 + 5". The answer will be 10 in a decimal format.
However, part of my validation is make the even indexes of the string array only be numbers, whilst the odd indexes of the string array can only be operators of "+", "-", "*", "/". How would I do this?
I have tried to do it here but I am struggling:
for (int index = 0; index <= calculatorInput.Length; index++)
{
if (index % 2 == 0)
{
if (Decimal.TryParse(calculatorInput[index]))
{
throw new CalculatorException("Even indexes must contain a number");
}
//check for number
}
else if (//code here)
{
throw new CalculatorException("Odd indexes must contain an operator");
//check for operator
}
}
Sorry if this question is too simple, but I would greatly appreciate the help!
My apologies for the late response. The comment from Rufus L (https://stackoverflow.com/users/2052655/rufus-l) helped to provide the solution I needed at the time.
decimal temp; if (decimal.TryParse(calculatorInput[index].ToString(), out temp)){} The TryParse method takes a string and an out parameter, which you are missing. But there are better ways to do what you want. – Rufus L Nov 1 '19 at 18:58
All answers and comments were very helpful in my development however. The calculator has been finished now though there is always room for improvement.
You can focus on operators for validation. They must always be somewhere inside the input string. Minus operator is an exception here if your calculator accepts negative numbers. But if the calculator is basic and does not support negative numbers, So the code below should be enough for operator validation:
string inputString = "10 + 10";
int index = inputString.IndexOf('+');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('*');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('/');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('-');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
///Calculation code
To increase readability I did not create a nested if-else statement.
After this code block, you can place your calculation code. I think it is enough for a new learner.

Substrings and Char.Is/Number Confusion. [closed]

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 7 years ago.
Improve this question
I'm a beginner at c# and how could I write a code that will check if:
the first 3 characters are letters
the next 3 are numbers,
next two letters
And the last character a number.
And if it is isn't write an error message.
I've tried using Substring(0,3) and putting it against Char.IsLetter just to attempt but failed.
Here's a correct way to do it using char.IsLetter and char.IsNumber.
if(myString.Length == 9
&& char.IsLetter(myString[0])
&& char.IsLetter(myString[1])
&& char.IsLetter(myString[2])
&& char.IsNumber(myString[3])
&& char.IsNumber(myString[4])
&& char.IsNumber(myString[5])
&& char.IsLetter(myString[6])
&& char.IsLetter(myString[7])
&& char.IsNumber(myString[8]))
{
// match.
}
Basically you have validate the length of the string, and then validate each character.
You could also use char.IsDigit to limit the match to radix-10 digit versus char.IsNumber that will match any Unicode character that is deemed a number (fractions, subscripts, superscripts, Roman numerals, currency numerators, encircled numbers, and script-specific digits). Also char.IsLetter will also match any Unicode character that is deemed a letter which will stray outside of the basic A-Z. To restrict numbers to 0-9 and letters to A-Z you could do this instead.
public static IsAtoZ(char c)
{
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
}
if(myString.Length == 9
&& IsAtoZ(myString[0])
&& IsAtoZ(myString[1])
&& IsAtoZ(myString[2])
&& char.IsDigit(myString[3])
&& char.IsDigit(myString[4])
&& char.IsDigit(myString[5])
&& IsAtoZ(myString[6])
&& IsAtoZ(myString[7])
&& char.IsDigit(myString[8]))
{
// match.
}
But honestly at this point a regular expression will be more terse. But note that you'll still have to consider if you want to match Unicode characters and use the correct regular expression based on that.
you can use a regex
bool isMatch= Regex.IsMatch("abc123de4", #"\p{L}{3}\d{3}\p{L}{2}\d");
You could just use a regular expression:
var regex = new Regex("^[a-z]{3}[0-9]{2}[a-z]{2}[0-9]{1}$", RegexOptions.IgnoreCase);
var matces = regex.Matches(input);
where input is the string you want to check.
When we pass the option RegexOptions.IgnoreCase to the constructor of the Regex, we say that it doesn't matter if the letters are capital or not.
You could avoid to specify this parameter and state explicitly that you want both capital and small letters, as Rahul has correctly pointed out in his comment. This is done like below:
var regex = new Regex("^[a-z][A-Z]{3}[0-9]{2}[a-z][A-Z]{2}[0-9]{1}$");
var matces = regex.Matches(input);
You can access the individual characters of a string in C# like this:
string s = "1test";
char c = s[0];
c will be '1' one then.
In the next step you can use the Char.IsNumber Method which returns a bool. Just like this:
if(c.IsNumber()){}
Then you do the same thing for the next two chars except that you use the Char.IsLetter method.
I think there are several elegant ways to do this. Since you said that you're a beginner to C#, I would suggest just finding the easiest (most pseudo-code-like, IMHO) way to just express the problem/solution:
private bool MatchesPattern(string test)
{
// can't possibly match the pattern with less than 9 chars
if (test.Length < 9) return false;
int idx = 0;
// test are letters
for (int steps = 1; steps <= 3; steps++)
{
if (!char.IsLetter(test[idx++])) return false;
}
// test are numbers
for (int steps = 1; steps <= 3; steps++)
{
if (!char.IsNumber(test[idx++])) return false;
}
// test are letters
for (int steps = 1; steps <= 2; steps++)
{
if (!char.IsLetter(test[idx++])) return false;
}
// test last char is number
if (!char.IsNumber(test.Last())) return false;
return true;
}
You can test the results:
private void Test(string testValue)
{
if (!MatchesPattern(testValue))
{
Console.WriteLine("Error!");
}
}

How to search for number in string with method Contains and Linq in c#?

I create calculator which have buttons with numbers and operators for basic operation (+, -,...) and just want to filter buttons with numbers to detect when is clicked number (between 0-9). Also i put new eventhadler which convert sender to button.
I wondering what will be nice and easy way to filter the buttons with numbers (using linq)
What did i try so far is
if(btn.Text == btn.Text.Contains(x => x >= '0' && x <= '9'))
MessageBox.Show("number " + btn.Text + " is pressed!");
How to make upper code workable?
Here you go, for your immediate needs:
if(btn.Text.All(char.IsDigit))
{
//Do your stuff
}
If all you want to know is that is it a number or not do this. No LINQ is required
LINQ Way to check the numbers are between 0 and 9
if(yourstring.ToCharArray().Where(c=> c < '0' || c > '9').Any())
return false;
else
return true;
To check that it contains a valid number
double num;
if (double.TryParse(btn.Text, out num))
{
// It's a number!
}
or to check less than 10 without linq
static bool IsLessThanTen(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
if you need to check at least one number in the button text, then use below
return btn.Text.Any(char.IsDigit)
If you writing calculator, you better check NCalc - Mathematical Expressions Evaluator for .NET and this CodeProject tutorial
This should work
bool hasNumeric = yourString.IndexOfAny("0123456789".ToCharArray()) > -1;

Central/middle letter of a string.(methods)

I need to solve the following question which i can't get to work by myself(newbie^^)..:
Ok, the question: Create a method which will print the central letter of a string (given as a parameter). I need to use the property lenght to determine the lenght.
So for example the string: Books. the middle/central letter is o.
Hope its a bit clear..
Thanks in advance.
Edit: I know how to determine the lenght of the string. Now the problem is to divide the word and then write down the next letter or something.
Here are some tips:
1. Type string has a Length property.
2 .If you know the index of the character you want, you can ask for it using: myString[index].
3. Knowing what to do with string that has even number of characters is necessary to answer that question.
4. Consider integer devision.
That should get you started.
string middleLetter(string arg)
{
return arg[arg.Length >> 1];
}
public static string FindMiddleChar(string s)
{
int middleChar = s.Length / 2;
if (s.Length > 2)
{
if (s.Length % 3 == 0)
{
if (s.Length <= 3)
{
return s[middleChar].ToString();
}
return s[middleChar - 1] + s[middleChar].ToString();
}
else if (s.Length % 3 != 0)
{
if (s.Length <= 4)
{
return s[middleChar - 1] + s[middleChar].ToString();
}
return s[middleChar].ToString();
}
}
return "Error, the input string must contain at least three characters.";
}

toString() of int e = 0000007 omits all zeros. How can I preserve them?

I'm trying to write a program in C# that takes in an int x and decides if it has exactly 7 digits. Right now I'm using x.toString().Length == 7 to check, but I noticed that if the number starts with 0, it automatically gets omitted and I get an incorrect answer (ie the program thinks the input length is less than 7)
Is there a way to fix this? Thanks in advance.
Edit: Sorry I should have mentioned, this was a program to collect and validate the format of ID numbers (so I didn't want something like 0000001 to default to 1) Thanks for the string input suggestion, I think I'm going to try that.
If you want to preserve the input formatting, you must not convert the input to an int. You must store it in a String.
You say your program takes an int. At that point you have already lost. You need to change that interface to accept String inputs.
If you don't care about leading zeros, you're really looking for 7 digits or less. You can check for:
x.toString().Length <= 7
or better:
x < 10000000
Maybe I'm wrong, but to me, 0000001 == 1, and 1 has one digit, not seven. So that's mathematically correct behaviour.
I think you could format it as a string:
int myInt=1;
myInt.ToString("0000000");
prints:
0000001.
so you could do:
if (myInt.ToString("0000000").Length==7)
You can simply write:
int input = 5;
if(input.ToString("0000000").Length == 7)
{
//do your stuff
}
No. It is perfectly valid for a numeric literal to have leading 0s, but a) many languages consider this to be an octal literal, and b) the leading 0s don't actually exist as part of the number. If you need a string then start with a string literal.
You should use string to check length count including 0.
Then I would like to ask "Why do you want to show 0000007? For What?"
You said you're asking for a int, but I suppose you're receiving it as string:
int i = 0;
string number = Console.ReadLine();
if (Int32.TryParse(number, out i))
{
//if (i.ToString().Length == 7) // you can try this too
if (i > 999999 && i < 10000000)
{
Console.WriteLine("Have exactly 7 digits");
}
else
{
Console.WriteLine("Doesn't have exactly 7 digits");
}
}
else
{
Console.WriteLine("Not an Int32 number");
}
This way you try to cast that received number as Int32 and, so, compare its length.
You can let the number be saved as an int with the omitted zeros. but then if you want the number displayed with the zeros then you can use an if statement and a while loop. for example,
Let's assume the values are stored in a numbers array and you need them to be stored as int so you can sort them but displayed as string so you can display with the leading zeros.
int[] numbers = new int[3];
numbers[0] = 001;
numbers[1] = 002;
numbers[2] = 123;
String displayed_Number;
for (int i = 0; i < numbers.Length; i++)
{
displayed_Number = numbers[i].ToString();
if (displayed_Number.Length == 3)
{
listBox.Items.Add(displayed_Number);
}
else if (displayed_Number.Length < 3)
{
while (displayed_Number.Length < 3)
{
displayed_Number = "0" + displayed_Number;
}
listBox.Items.Add(displayed_Number);
}
}
The output is 001 002 123
That way you can maintain the zeros in the numbers when displayed. and they can be stored as int in case you have to store them as int.

Categories

Resources