Hello i have an inputtextfield were i want to put figures for example 100 to have a script loop for 100 times, but im getting an error all the time. When putting a number at the place it does run normal, i'm trying to feed it with a number from the textbox.
for (var i = 0; i < (textBox2.Text); i++)
{
code in here
}
Here's the error : Error 1 Operator '<' cannot be applied to operands of type 'int' and 'string'
What am i doing wrong? Can someone help me??
You give textBox2.Text although it would have number but it has type string and you need integer.
int result = int.Parse(textBox2.Text);
for (var i = 0; i <result ; i++)
{
//Your code
}
Check if the text can be Parsed to an int first and then proceed. Following int.TryParse() method will return true if textBox2.Text.Trim() is an int
int limit;
if( int.TryParse(textBox2.Text.Trim(), out limit))
{
for (var i = 0; i < limit ; i++)
{
//code in here
}
}
The error message is quite clear, you're trying to compare an integer to a string value. That obviously won't work. You need first to cast the value from the textbox to integer type, than you can apply the condition for the for-loop.
Use Int.Parse(txtFirst.Text);
One thing, you seem to be a beginner, I want you to follow naming conventions in coding like txt prepended to the name of textbox, lbl for label and you can find more in your study material...
You need to parse the textBox2.Text String to get an int. For instance:
int x = int.Parse(textBox2.Text);
for (var i = 0; i < x; i++)
As others have mentioned, textbox2.text is a string and must be converted to a #n integer
for (var i = 0; i < int.Parse(textBox2.Text); i++)
{
//code in here
}
However, i wound recommend you use a more appropriate control, such as a numeric Up Down:
for (var i = 0; i < Convert.ToInt32(numericUpDown1.Value); i++)
{
code in here
}
The value in textBox2.Text is of type string , you need to cast it to int.
This is done by cint() function
cint(textBox2.Text)
or Parse() method
Int32.Parse(textBox2.Text);
THe above two methods will work if you are sure the input string is valid that contains something like "123" rather than "absjsdfd".
for (var i = 0; i < Int32.Parse(textBox2.Text); i++)
{
//your code in here
}
To avoid throwing exception if invalid input is entered in textbox use a more robust function Integer.TryParse()
int limit;
bool valid = int.TryParse(textbox2.Text, out limit);
if(valid)
for (var i = 0; i < limit; i++)
{
//your code in here
}
You need to use the Int32.Parse() method to convert the text in the textbox to an integer. The Text field is only an string and the compiler cannot figure out what you are trying to do.
Related
I'm trying to make a shortcut from making several different "if statements". Instead I only change one value that is given by a for loop.
"KeyCode.Alpha1" suggests that I press the "1" key on the top of the keyboard and so on.
So the "numberKey" variable has a string stored "Alpha1" but it's reading it as just "numberKey". Then i get a error message saying 'KeyCode' does not contain a definition for 'numberKey'. Help
private void Inventory()
{
for (int i = 1; i <= items.Count; i++)
{
string numberKey = "Alpha" + i.ToString();
if (Input.GetKeyDown(KeyCode.numberKey))
{
items[currentItem].gameObject.SetActive(false);
currentItem = i--;
items[currentItem].gameObject.SetActive(true);
}
}
}
KeyCode is an enum so you can't just dynamically build a string with the same name as an enum and expect it to work. Instead use Enum.Parse:
Input.GetKeyDown(Enum.Parse(typeof(KeyCode), numberKey, true));
Enum.Parse takes the text representation of an Enum and makes the enum from it. So it's basically saying "Return the KeyCode enum entry where the name is equal to numberKey" The boolean at the end tells it not to be case sensitive.
You might try casting between enum and int:
int Alpha0Key = (int)KeyCode.Alpha0;
for (int i = 0; i < items.Count; i++)
{
if (Input.GetKeyDown((KeyCode)(Alpha0Key+i))
{
items[currentItem].gameObject.SetActive(false);
currentItem = i;
items[currentItem].gameObject.SetActive(true);
}
}
I have an assignment where the I gotta figure out a way to make the input read both double and decimal and perform a few operations as new method.
char[] charSeparators = new char[] { ' ' };
Console.Write("Please type few numbers: ");
dynamic[] test = Console.ReadLine().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray();
dynamic value = test[0];
for (int i = 1; i < test.Length; i++)
{
if (test[i] < value)
{
value = test[i];
}
}
I figured out to use dynamic as data type, but this throws an exception:
Operator '<' cannot be applied to operands of type 'string' and 'string'
I already made a fallback using a switch where the user selects if it's double or decimal but I thought this was way more simple.
How to stop that dynamic from being read as string ?
Note that the split method always returns an array of strings, so you have to convert it results. The problem isn't the Dynamic.
Example:
char[] charSeparators = new char[] { ' ' };
Console.Write("Please type few numbers: ");
dynamic[] test = Console.ReadLine().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray();
double value = double.Parse(test[0]);
for (int i = 1; i < test.Length; i++)
{
if (double.Parse(test[i]) < value)
{
value = double.Parse(test[i]);
}
}
try this:
var value= Convert.ToDecimal( test[0])
or
var value= Convert.ToDouble( test[0])
because test[0] is a string, so when you define it as dynamic, its type binds in run time but makes no difference because its type is clear in compile-time and no need to define it as dynamic.
You are taking the console input which will be a string. In order to turn in into any sort of numeric value you need to parse it.
dynamic[] test = Console.ReadLine().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray(); will be a string array, so you'll need to cast it to a decimal or a double.
I'm not sure how you're going to figure out whether it's double of decimal, so why not cast them all to decimal, since that type keeps its precision.
Your current array contains strings. You need to convert them to decimals or doubles
dynamic[] test = Console.ReadLine().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray().Select(double.Parse).ToArray();
In aspx page i have a textbox
<asp:TextBox ID="txtrandom" runat="server"></asp:TextBox>
In .cs page i am retrieving te value from that text box and converting it into int so that it can be used in for loop.
In .cs page
int random;
random = Convert.ToInt16(txtrandom.Text);
for (int i = 0; i < random; i++)
{
//other code
}
But When i am executin it will give error as Input string was not in correct format.How to convert it into int?
Plz try below code
int random=0;
bool isValidInt = int.TryParse(txtrandom.Text, out random);
if (isValidInt)
{
for (int i = 0; i < random; i++)
{
//other code
}
}
else
{
Response.Write("Please enter valid int value in textbox.");
txtrandom.Focus();
}
Thanks
First of all you need to understand that "Converting a value to integer must needed the converted value to be an int type". The value entered in the textbox is a type of string so it may be any type.
So first you need to check for a valid INT value. For that you need to do like this
int random = 0;
bool isValidInt = int.TryParse(txtrandom.Text, out random);
If conversion is successful then you can use the valid integer value which is now in random
And the code will look like (Ref: Hitesh's answer)
if (isValidInt)
{
for (int i = 0; i < random; i++)
{
//other code
}
}
else
{
Response.Write("Please enter valid int value in textbox.");
txtrandom.Focus();
}
You should use text box as number type and for Int conversion you can use
int someInt;
int.TryParse(s, out someInt);
so return value indiacate whether the conversion Int32 succeeded or not.
These are the recommended methods..
int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);
Firstly you need to make sure that only numbers are entered into that text box. so that you are not facing any exception while converting it to an integer value.
Use a regular expression validator to make sure that only Integers are entered into that Textbox with validation expression ^[0-9]+$
Also You need to be consistent on what datatype you are using. Use Int32
then
if(!Textbox1.Text.Equals("")) // you can take care of "" by using required field validator
{
Int32 random = Convert.ToInt32(Textbox1.Text);
}
Now use this value accordingly.
My problem is that I want to make a program that uses two lists, which is almost impossible for me to understand. Okay, so the deal is that I want to make a program where you first type in a city name and then the temperature for the city. This is where the relationship comes from.
I have started by making a "list class", which looks like this:
class citytemp
{
private string city;
private double temp;
public citytemp(string city, double temp)
{
this.city = city;
this.temp = temp;
}
public string City
{
get { return city; }
set { city = value; }
}
public double Temp
{
get { return temp; }
set { temp = value; }
}
}
Then I make the list in the program like this
List<citytemp> temps = new List<citytemp>();
Which all looks good to me. But when I'm trying to show the user the list nothing shows up. I use these lines to show it:
for (int i = 0; i > temps.Count; i++)
{
Console.WriteLine(temps[i].City, temps[i].Temp);
}
BTW: I add "things" to the list by these rows:
temps.Add(new citytemp(tempcity, temptemp));
...where tempcity and temptemp are temporary variables. They are only there to make it more simple for me to add them to the list, since I'm using a switch statement to add them to the list.
To make things more clear, my problem is that I don't know how I'm suppose to show the list to the user in the program.
Your problem is in the for loop. Change it to this
for (int i = 0; i < temps.Count; i++)
i.e. change the greater than > operator to a less than <
You have an error in your for loop.
for (int i = 0; i > temps.Count; i++)
it should be:
for (int i = 0; i < temps.Count; i++)
First of all, I'm not sure what you mean by "2 lists" as you only have one list in your code.
However, the problem you're having with "nothing shows up" is easy to fix.
This line of code:
for (int i = 0; i > temps.Count; i++)
Should be read as follows:
i = 0;
while (i > temps.Count)
{
... rest of your loop body here
i++;
}
if you read this, you'll notice that the second part of the for statement is not when to terminate but how long to keep going.
Change it to this, and you should be good:
for (int i = 0; i < temps.Count; i++)
^
+-- changed from >
I think a hashtable, specifically a dictionary would help you here:
var cityTemps = new Dictionary<string, double>();
cityTemps.Add("TestCity", 56.4);
foreach (var kvp in cityTemps)
Console.WriteLine("{0}, {1}", kvp.Key, kvp.Value);
In addition to the loop that has been mentioned, be careful withConsole.WriteLine because it takes in a String as first argument which it assumes is a format and object[] params as a second parameter. When you pass temps[i].City to it since its String it will think that its the format and temps[i].Temp is the parameter and won't display correctly.
What you want instead:
Console.WriteLine("City: {0} Temp: {1}", temps[i].City, temps[i].Temp);
Here I am using "City: {0} Temp: {1}" as the format for the string and the proper parameters.
This answer is to save you a headache later on wondering why only the city name is being displayed.
The following is an extract from my code:
public class AllIntegerIDs
{
public AllIntegerIDs()
{
m_MessageID = 0;
m_MessageType = 0;
m_ClassID = 0;
m_CategoryID = 0;
m_MessageText = null;
}
~AllIntegerIDs()
{
}
public void SetIntegerValues (int messageID, int messagetype,
int classID, int categoryID)
{
this.m_MessageID = messageID;
this.m_MessageType = messagetype;
this.m_ClassID = classID;
this.m_CategoryID = categoryID;
}
public string m_MessageText;
public int m_MessageID;
public int m_MessageType;
public int m_ClassID;
public int m_CategoryID;
}
I am trying to use the following in my main() function code:
List<AllIntegerIDs> integerList = new List<AllIntegerIDs>();
/* some code here that is ised for following assignments*/
{
integerList.Add(new AllIntegerIDs());
index++;
integerList[index].m_MessageID = (int)IntegerIDsSubstring[IntOffset];
integerList[index].m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
integerList[index].m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
integerList[index].m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
integerList[index].m_MessageText = MessageTextSubstring;
}
Problem is here: I am trying to print all elements in my List using a for loop:
for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++) //<----PROBLEM HERE
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", integerList[cnt3].m_MessageID,integerList[cnt3].m_MessageType,integerList[cnt3].m_ClassID,integerList[cnt3].m_CategoryID, integerList[cnt3].m_MessageText);
}
I want to find the last element so that I equate cnt3 in my for loop and print out all entries in the List. Each element in the list is an object of the class AllIntegerIDs as mentioned above in the code sample. How do I find the last valid entry in the List?
Should I use something like integerList.Find(integerList[].m_MessageText == null;?
If I use that it will need an index that will range from 0 to whatever maximum. Means I will have to use another for loop which I do not intend to use. Is there a shorter/better way?
To get the last item of a collection use LastOrDefault() and Last() extension methods
var lastItem = integerList.LastOrDefault();
OR
var lastItem = integerList.Last();
Remeber to add using System.Linq;, or this method won't be available.
If you just want to access the last item in the list you can do
if (integerList.Count > 0)
{
// pre C#8.0 : var item = integerList[integerList.Count - 1];
// C#8.0 :
var item = integerList[^1];
}
to get the total number of items in the list you can use the Count property
var itemCount = integerList.Count;
In C# 8.0 you can get the last item with ^ operator full explanation
List<char> list = ...;
var value = list[^1];
// Gets translated to
var value = list[list.Count - 1];
Lets get at the root of the question, how to address the last element of a List safely...
Assuming
List<string> myList = new List<string>();
Then
//NOT safe on an empty list!
string myString = myList[myList.Count -1];
//equivalent to the above line when Count is 0, bad index
string otherString = myList[-1];
"count-1" is a bad habit unless you first guarantee the list is not empty.
There is not a convenient way around checking for the empty list except to do it.
The shortest way I can think of is
string myString = (myList.Count != 0) ? myList [ myList.Count-1 ] : "";
you could go all out and make a delegate that always returns true, and pass it to FindLast, which will return the last value (or default constructed valye if the list is empty). This function starts at the end of the list so will be Big O(1) or constant time, despite the method normally being O(n).
//somewhere in your codebase, a strange delegate is defined
private static bool alwaysTrue(string in)
{
return true;
}
//Wherever you are working with the list
string myString = myList.FindLast(alwaysTrue);
The FindLast method is ugly if you count the delegate part, but it only needs to be declared one place. If the list is empty, it will return a default constructed value of the list type "" for string. Taking the alwaysTrue delegate a step further, making it a template instead of string type, would be more useful.
int lastInt = integerList[integerList.Count-1];
Though this was posted 11 years ago, I'm sure the right number of answers is one more than there are!
You can also doing something like;
if (integerList.Count > 0)
var item = integerList[^1];
See the tutorial post on the MS C# docs here from a few months back.
I would personally still stick with LastOrDefault() / Last() but thought I'd share this.
EDIT;
Just realised another answer has mentioned this with another doc link.
Change
for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++)
to
for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
Use the Count property. The last index will be Count - 1.
for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
Why not just use the Count property on the List?
for(int cnt3 = 0; cnt3 < integerList.Count; cnt3++)
Independent of your original question, you will get better performance if you capture references to local variables rather than index into your list multiple times:
AllIntegerIDs ids = new AllIntegerIDs();
ids.m_MessageID = (int)IntegerIDsSubstring[IntOffset];
ids.m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
ids.m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
ids.m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
ids.m_MessageText = MessageTextSubstring;
integerList.Add(ids);
And in your for loop:
for (int cnt3 = 0 ; cnt3 < integerList.Count ; cnt3++) //<----PROBLEM HERE
{
AllIntegerIDs ids = integerList[cnt3];
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n",
ids.m_MessageID,ids.m_MessageType,ids.m_ClassID,ids.m_CategoryID, ids.m_MessageText);
}
I would have to agree a foreach would be a lot easier something like
foreach(AllIntegerIDs allIntegerIDs in integerList)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", allIntegerIDs.m_MessageID,
allIntegerIDs.m_MessageType,
allIntegerIDs.m_ClassID,
allIntegerIDs.m_CategoryID,
allIntegerIDs.m_MessageText);
}
Also I would suggest you add properties to access your information instead of public fields, depending on your .net version you can add it like public int MessageType {get; set;} and get rid of the m_ from your public fields, properties etc as it shouldnt be there.