I'm new in c# and unity and Wondering how could I write this code to check if two string lengths are equal.
with this code unity system shows this error:
error CS1061: Type char' does not contain a definition forLength' and no extension method Length' of typechar' could be found.
for (int i = 0; i < Answers.Length; i++)
{
if (GetAnswer[i].Length == Answers[i].Length)
{
//Do something
}
}
if (yourString.Length == yourOtherString.Length)
{
//dosomething
}
should check if a string is equals in length to another
The problem with your code is that a string is an array of char so it calculate the length of the char (Which do not exist)
for (int i = 0; i < Answers.Length+1; i++)
{
if (GetAnswer.Length == Answers.Length)
{
//Do something
}
}
You also need to increment the value of the for to get the correct length otherwise the Answers.Length will always be short of 1
Related
I have an array of strings. I want to compare with the string which I am getting from JSON. Comparision should be like this.
For example:
If Account name in one string is Google and in other it is Google Inc, then since Google is part of the Google Inc company name, It should get matched. Otherwise not.
Code which I have written:
for (int i = 0; i < accountCount; i++)
{
//// account is found in the array
name[i] = account.Entities[i].Attributes["name"].ToString();
if (name[i] == message.Current.org_name)
{
flag = 1;
c.CreateOpportunity(message);
break;
}
}
//// account is not found in the array
if (flag == 0)
{
c.CreateAccount(message);
c.CreateOpportunity(message);
}
Try to use Contains function instead :
for (int i = 0; i < accountCount; i++)
{
//// account is found in the array
name[i] = account.Entities[i].Attributes["name"].ToString();
if (name[i].Contains(message.Current.org_name)
|| message.Current.org_name.Contains(name[i]))
{
flag = 1;
break;
}
}
//// account is not found in the array
if (flag == 0)
c.CreateAccount(message);
c.CreateOpportunity(message);
You can use Contains for a case sensitive search
or IndexOf to speficify more options with comparison criteria
However for the fun of it we can use Any on an array or list
Note : none of the above check for null
Contains
var org = message.Current.org_name;
var found = account.Entities.Any( // does any entity contain org ?
x => x.Attributes["name"] // Get Attribute
.ToString() // Convert it to string if needed
.Contains(org));
if (found)
{
c.CreateAccount(message);
}
c.CreateOpportunity(message);
if you would like a case insensative search you can use String.IndexOf
IndexOf
var found = account.Entities.Any( // does any entity contain org ?
x => x.Attributes["name"] // Get Attribute
.ToString() // Convert it to string if needed
.IndexOf(org, StringComparison.OrdinalIgnoreCase) >= 0);
References
String.Contains -
String.Contains Method (String)
String.IndexOf -
String.IndexOf Method (String, StringComparison)
Coparison type - StringComparison Enumeration
I tried to compare scene name but I am getting the error below:
error CS0019: Operator ==' cannot be applied to operands of type
method group' and `string'
I can't figure out how to fix this error. please help me! the error is located on the arrow
void CheckCurrentLevel()
{
for(int i = 1; i < LevelAmount; i++)
{
---> if (SceneManager.LoadScene == "Level" + i) {
CurrentLevel = i;
SaveMyGame ();
}
}
}
SceneManager.LoadScene is a void function used to load a scene. It does not return anything so you can't compare it with a string.
It looks like you want to compare the current scene name with "Level" + i. If that's true then you are looking for SceneManager.GetActiveScene().name
void CheckCurrentLevel()
{
for (int i = 1; i < LevelAmount; i++)
{
if (SceneManager.GetActiveScene().name == "Level" + i)
{
CurrentLevel = i;
SaveMyGame();
}
}
}
Keep in mind that the == operator Checks if the values of two operands are equal or not, subject to the condition that both the operands should be same type. From the error message it is clear that LoadScene is defined as a method.
Your code will works fine if you use like this:
if (SceneManager.LoadScene(params if any) == "Level" + i)
{
// Code here
}
Subject to the condition that LoadScene() method should return a string object or else the return type will be a business object in this case use a string property for comparison
I am looping through a list and would like to add multiple occurrences, should I find them.
so far I have,
public struct optionsSort
{
public string name;
public string date;
public double strike;
public string callPut;
public double size;
public string isin;
}
List<List<optionsSort>> stocks = new List<List<optionsSort>>();
optionsSort tempStock1 = new optionsSort();
List<optionsSort> posCheckOptions = new List<optionsSort>();
then some code, then,
for(int k = 0; k<posCheckOptions.Count; k++)
{
for(int l = 0; l<posCheckOptions[l].Count; l++)
{
if(posCheckOptions[l+1] == null)
{
//finished the iteration
break;
}
else if
(posCheckOptions[k][l + 1].date == posCheckOptions[k][l].date
&& posCheckOptions[k][l + 1].strike == posCheckOptions[k][l].strike
&& posCheckOptions[k][l + 1].callPut == posCheckOptions[k][l].callPut)
{
posCheckOptions[k][l].size = posCheckOptions[k][l].size
+ posCheckOptions[k][l + 1].size;
}
}
}
Basicly, Im looking forward from the start of the list. asking the question, are certain elements of the list at i+1 the same as i, if so, add those elements to i and delete the entire row.
i get this error
"Error 1 Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable C:\Users\WindowsFormsApplication1\WindowsFormsApplication1\ReadCSV.cs 890 25 WindowsFormsApplication1
"
Many Thanks for looking.
I believe your problem is that you are using a mutable struct. Mutable structs are evil.
The simplest solution is to change optionsSort to a class. That should fix the error message.
To explain the error message, when you call posCheckOptions[k][l], since optionsSort is a struct, it returns a copy of the value in the list. When you change size, it will update the copy, but not the one in the list. The copy would then be discarded. The compiler recognizes this and stops you.
I recommend you read up on the differences between reference types and value types.
This question already has answers here:
c# switch problem
(8 answers)
Closed 9 years ago.
I am getting the following error. Use of unassigned local variable markduplicate. I don't understand why? This program finds a duplicate in an array. I been trying to figure it out and I feel like im so close. Thanks for the help.
using System;
class duplicate
{
static void Main()
{
const int Array_Size = 5;
int [] number = new int [Array_Size];
int i;
for ( i = 0; i < Array_Size; i++)
{
Console.Write("Element " + i + ": ");
number[i] = Int32.Parse(Console.ReadLine());
if (number[i] < 9 || number[i] > 101)
{
Console.WriteLine("Enter Number between 10 - 100");
number[i] = Int32.Parse(Console.ReadLine());
}
}
bool markduplicate;
for (i = 0; i < Array_Size; i++)
{
for (int j = 0; j < Array_Size; j++)
{
if (i != j)
{
if (number[j] == number[i])
{
markduplicate = true;
}
}
if (markduplicate != true)
{
Console.WriteLine("Element " + i + " " + number[i]);
}
}
}
}
}
This is because the C#'s code analyzer detected that there are paths through you program when the markduplicate's value would be referenced before any assignments to it are made. Specifically, this is going to happen during the very first iteration of the nested loop, when both i and j are zero: the if (i != j) block containing the assignment is not going to execute, so the value of the markduplicate is going to get retrieved in the very next if statement.
To fix this problem, change
bool markduplicate;
to
bool markduplicate = false;
in the declaration.
The compiler thinks it is possible for you to hit the if (markduplicate != true) line before markduplicate has been set.
If you think the compiler is wrong, give it a value when declaring e.g. bool markduplicate = true;. If you analyze and think the compiler is correct, adjust you code accordingly.
Also: if (markduplicate != true) is considered poor style. Use if(!markduplicate) instead.
You've declared the boolean variable markduplicate but you haven't given it an initial value - the compiler doesn't know if it should be initially true or false.
In this case it's clear you want it to be initially false, so put this:
bool markduplicate = false;
it will now compiled.
In your code, (i != j) is false before it is true and therefore you are checking the value of your variable which has had nothing assigned to it.
You need to either assign a value to markduplicate at its declaration or you need to make sure that any path that leads to a conditional check on its value has a value assigned to it first.
You have to assign markdefault to either true or false in your declaration. Otherwise, if number [j] != number [i], then markdefault will not be assigned and if markduplicate != true cannot be evaluated.
I have been up half the night and still trying to get this null exception figured out. I have read a few of texts about this issue but none has helped me in any way, to me what the problem is as it should work :/ It just crashes at this piece of code:
Private void UpdateGUI()
{
string selectedItem = cmbDisplayOptions.Items[cmbDisplayOptions.SelectedIndex].ToString();
rdbtReserv.Checked = true;
lstReservations.Items.Clear();
lstReservations.Items.AddRange(m_seatMngr.GetSeatInfoStrings(selectedItem));
}
lstReservations.Items.AddRange(m_seatMngr.GetSeatInfoStrings(selectedItem)); Gives me the ArgumentNullExeption, but to me it should not do that.
the addrange sends string selectedItem to another class:
public string[] GetSeatInfoStrings(string selectedItem)
{
int count = GetNumOfSeats(selectedItem);
if (count <= 0)
{
return null;
}
string[] strSeatInfoStrings = new string[count];
for (int index = 0; index <= m_totNumOfSeats - 1; index++)
{
strSeatInfoStrings[index] = GetSeatInfoAt(index);
}
return strSeatInfoStrings;
}
This int count = GetNumOfSeats(selectedItem); goes to here and returns with an int:
private int GetNumOfSeats(string selectedItem)
{
if (selectedItem == "ReservedSeats")
{
return GetNumReserved();
}
if (selectedItem == "VacantSeats")
{
return GetNumVacant();
}
else
{
return m_totNumOfSeats;
}
}
I have checked the arrayed have the correct number of spaces(60) and that selectedItem has a string(Allseats to start with so it should return m_totnumOfSeats which is an int of 60) But then in the private int GetNumOfSeats something goes wrong and it returns null and...well why?
I can't see the problem.. maybe gone blind by trying to find the issue. Always got outstanding help here and I have learned tons!! So maybe someone can point out all the issues there is in my code.
Thanks a million in advance for any and all advice!
//Regards
Check if your variables are actually initialized and returns correct values.
There are logical errors in the GetSeatInfoStrings methods and the GetNumofSeats method.
Lucky for you the GetNumOfSeats method will always return 60 for you because of the wrong way you compare strings. It's not the right way, so use the Equals method for comparison like
if (selectedItem.Equals("ReservedSeats"))
With that you will get a proper output form GetNumOfSeats(string) method.
The next thing is to fix your looping in the GetSeatInfoStrings method so as to not get an array index out of bounds exception like this.
string[] strSeatInfoStrings = new string[count];
for (int index = 0; index <= count; index++)
{
strSeatInfoStrings[index] = GetSeatInfoAt(index);
}
return strSeatInfoStrings;
Also fix the part where your logic returns a null in the GetSeatInfoStrings method. it should return an empty string array according to your logic as
return new string[0];
That should probably get your methods working. You need to be very careful of what you code before you debug it :-)
Looking at the source code of ObjectCollection, when you call AddRange and pass a null value, you get back the ArgumentNullException.
You could prevent this changing this code
if (count <= 0)
{
return new string[0];
}