Searching array is not returning any results - c#

I have the following code that is suppose to search an array :
for (int i = 0; i < this.passwordList.Length; i++)
{
string userInput = Convert.ToString(this.passInput);
if(userInput == passwordList[i])
{
MessageBox.Show("FOUND");
foundResult = 1;
break;
}
//MessageBox.Show();
}
and the array has the following results :
public string[] passwordList = {"123456", "145784" , "asasas"};
What am I doing wrong!?!?

The mistake is probably here:
string userInput = Convert.ToString(this.passInput);
If you have a WinForms control, try something like this instead:
string userInput = this.passInput.Text;
You might also want to inspect the value of userInput in a debugger to make sure that it contains the value that you expect.

You havn't provided information about all your variables, but I suspect the the line
string userInput = Convert.ToString(this.passInput);
is the problem. If this.passInput is a control you will get the name of the type of the control and not what the user entered into the control.
If that is true you can simplify your code into something like this:
if (passwordList.Contains(this.passInput.Text)) {
MessageBox.Show("FOUND");
foundResult = 1;
}

Related

Make a method that contains a linear search?

I'm new to programmning and I'm taking a course to learn the basics in c#.
Right now I'm doing a console application that are supposed to work as a blog. In the application the user should be able to write a new post, show written posts and search for written posts. The application is supposed to be a list that contains arrays.
I'm almost finished with the application but I want to make a method for the linear search that searches for the written blogposts but I cant get it to work.
Here's the code for the linear search:
case 3:
Console.Write("Write the title for the post you are searching for: ");
string searchedWord = Console.ReadLine();
bool search = false;
for (int i = 0; i < myBlog.Count; i++)
{
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
{
search = true;
Console.WriteLine("\nHe post you are looking for exists in the blog:");
Console.WriteLine("\nTitle: " + myBlog[i][0] +
"\nPost: " + myBlog[i][1] +
"\n\nPress enter to return to the menu...");
}
}
if (search == false)
{
Console.WriteLine("The searched word wasn't found. Press enter to return to the menu...");
}
break;
I made a try creating a method for it but I'm doing wrong, can somebody please tell me how to do it?
static string BlogSearch(List<string[]> myBlog, string searchedWord)
{
for (int i = 0; i < myBlog; i++)
{
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
return i;
}
return -1;
}
If you are allowed to use Linq, you can do
using System.Linq;
//....
static string[] BlogSearch(List<string[]> myBlog, string searchedWord)
{
// "give me from myBlog ...
// the first element, that fits the criteria OR
// default if such an element is not in the list"
return myBlog.FirstOrDefault(x => x[0].Contains(searchedWord, StringComparison.OrdinalIgnoreCase));
}
See it in action in a Fiddle
Mind that this returns default(string) (which is null) if the searchedWord is not found.
I guess you are using string[] because your class (pun intended) has not come across the concept of classes, yet. So I won't go into that. Just so much: usually, you would model your blog data into a class with specific properties. And later on, you would probably want to keep the data in a Database instead of memory ... but all that is not really related to the problem at hand.
If you are NOT allowed to use Linq:
static string[] BlogSearch(List<string[]> myBlog, string searchedWord)
{
for( int i = 0; i < myBlog.Count; i++ )
{
if( myBlog[i][0].Contains(searchedWord, StringComparison.OrdinalIgnoreCase))
{
return myBlog[i];
}
}
return null;
}
Which is basically the same as the Linq version just coded out explicitly.
See it in action in a Fiddle.
Usage
// ... case 3: ...
var result = BlogSearch(myBlog, searchedWord);
if( result is null )
{
Console.WriteLine("The searched word wasn't found. Press enter to return to the menu...");
}
else
{
Console.WriteLine("\nThe post you are looking for exists in the blog:");
Console.WriteLine("\nTitle: " + result[0] +
"\nPost: " + result[1] +
"\n\nPress enter to return to the menu...");
}
break;
Some hints for you concerning your code:
// You expect to be returning `string`
// but all return statements return `int`.
// vv What you actually need is `string[]`, though.
static string BlogSearch(List<string[]> myBlog, string searchedWord)
{
// vv that's a `List<T>`, so you need `myBlog.Count` here
for (int i = 0; i < myBlog; i++)
{
// Two caveats:
// 1. _Exact_ match
// 2. `ToUpper` does not always work correctly.
// It is advised to use overloads with `StringComparison` argument
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
return i;
}
return -1;
}

Can't add objects to an array after a foreach loop in C#

I can't append an object to an array after a foreach loop. The object is okay, it contains all the right values which I found out through debugging.
In the end I want to have a custom Exercise object which contains a user-chosen number of custom ExerciseAnswer objects also. The array of ExerciseAnswer objects is the problem.
Here is the interesting part of my method:
static void CreateNewExerciseTest()
{
string? exerciseName = "Test Exercise";
string? exerciseTopic = "Test";
string exerciseQuestion = "Does it work?";
int numberOfAnswers = 2;
int numberOfApplicableAnswers = 0;
ExerciseAnswer[] exerciseAnswers = new ExerciseAnswer[2];
foreach (ExerciseAnswer answer in exerciseAnswers)
{
int exerciseAnswerId = GenerateId();
Console.WriteLine("\nEnter a name for this Exercise answer: ");
string? exerciseAnswerName = Console.ReadLine();
Console.WriteLine("Enter this answer for the Exercise: ");
string exerciseAnswerContent = Console.ReadLine();
Console.WriteLine("Enter y (yes) if this Exercise answer is applicable,
otherwise press n (no) or any other key: ");
char applicableAnswer = Console.ReadKey().KeyChar;
bool applicable = ExerciseAnswer.EvaluateExerciseAnswer(applicableAnswer);
if (applicable == true)
{
numberOfApplicableAnswers++;
}
ExerciseAnswer exerciseAnswer = new ExerciseAnswer(exerciseAnswerId,
exerciseAnswerName, exerciseAnswerContent, applicable);
exerciseAnswers.Append(exerciseAnswer);
// ...
}
}
This the GenerateId method:
static int GenerateId()
{
return ++id;
}
The array exerciseAnswers does not contain the ExerciseAnswer elements it should while the exerciseAnswer object in the line above does. Maybe the problem is related to the declaration and initialization of exerciseAnswers and the foreach loop.
Has somebody have an idea?
Thank you!
I believe you are using Append method from System.Linq namespace
public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element);
This method returns a new IEnumerable which contains your exerciceAnswer
With this piece of code you can understand what is going on:
var result = exerciseAnswers.Append(exerciseAnswer);
Console.WriteLine($"exerciseAnswers count = {exerciseAnswers.Count()}");
Console.WriteLine($"result count = {result.Count()}");
Console output:
exerciseAnswers count = 2
result count = 3
Append will just append to existing elements of array, since in your case size is already defined as 2(new ExerciseAnswer[2]) so it is not appending anything. What you can do is either have a new array and get the elements added to it or just get the index of element you are running the loop and replace same in the array.
Something like below:-
int elementIndex = Array.IndexOf(exerciseAnswers,answer);
exerciseAnswers[elementIndex] = exerciseAnswer;

C# user input int to array

I'm asking the user to input 5 numbers and store it into an array so I can send the values in a method and subtract 5 numbers from each array. When I use the:
for(I=0;I<5;I++) {
int[] val = Console.ReadLine();}
It says I can't convert int[] to int. I'm a little rusty in my programming. I also don't know how to send the array values from the main to the method.
You're assigning the string input from the Console to an array of int. This is wrong for two reasons:
int arrays (int[]) are a collection of ints.
The value you're getting from the Console isn't an int and needs to be parsed first.
This is a slight diversion, but I also don't think you should be using an array. Arrays generally have significantly less function in C# than the built-in List<T>. (All the rockstars chime in here) Some people say there's no reason to use arrays at all - I won't go that far, but I think for this use case it'll be a lot easier to just add items to a List than to allocate 5 spaces and initialize values by index.
Either way, you should use int.TryParse(), not int.Parse(), given that you'll immediately get an exception if you don't check if the user input was parseable to int. So example code for taking in strings from the user would look like this:
List<int> userInts = new List<int>();
for (int i = 0; i < 5; i++)
{
string userValue = Console.ReadLine();
int userInt;
if (int.TryParse(userValue, out userInt))
{
userInts.Add(userInt);
}
}
If you'd still like to use the array, or if you have to, just replace List<int> userInts... with int[] userInts = new int[5];, and replace userInts.Add(userInt) with userInts[i] = userInt;.
You initialize the array first
int[] val = new int[5];
and then when you do a for loop:
for (int i=0; i<val.Length; i++)
{
val[i] = int.Parse(Console.ReadLine());
}
Hint: To send the array values from main to the method, just look at how static void main is formed:
static void Main(string[] args)
Meaning main is accepting a string array of of console arguments.
You just need to parse the string being entered from the console to int first.You accept int by doing:
for(int i=0;i<myArray.Length;i++) {
myArray[i] = int.Parse(Console.ReadLine()); //Int32.Parse(Console.ReadLine()) also works
Just like #Furkle said, it is always best to use TryParse() which enables you to perform exception handling. MSDN has a nice tutorial on this.
furkle is correct, it's not working because the console.ReadLine method returns a string, and you can't assign a string to an int array. However, the solution provided is a bit clunky because it only reads one character at a time from the console. It's better to take in all the input at once.
Here is a short console program that
takes in a space separated list of integers from the user
converts the string to a string List using Split(' ').ToList();
Converts the string List to an int List
Reads the contents back to you.
Error handling is included.
static void Main(string[] args){
var intList = new List<int>();
string sUserInput = "";
var sList = new List<string>();
bool validInput = true;
do
{
validInput = true;
Console.WriteLine("input a space separated list of integers");
sUserInput = Console.ReadLine();
sList = sUserInput.Split(' ').ToList();
try
{
foreach (var item in sList) {intList.Add(int.Parse(item));}
}
catch (Exception e)
{
validInput = false;
Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
}
} while (validInput == false);
Console.WriteLine("\r\nHere are the contents of the intList:");
foreach (var item in intList)
{
Console.WriteLine(item);
}
Console.WriteLine("\r\npress any key to exit...");
Console.ReadKey();
}//end main
If you want to make sure the user only enters a total of 5 integers you can do the DO WHILE loop like this:
do
{
validInput = true;
Console.WriteLine("input a space separated list of integers");
sUserInput = Console.ReadLine();
sList = sUserInput.Split(' ').ToList();
if (sList.Count > 5)
{
validInput = false;
Console.WriteLine("you entered too many integers. You must enter only 5 integers. \r\n");
}
else
{
try
{
foreach (var item in sList) { intList.Add(int.Parse(item)); }
}
catch (Exception e)
{
validInput = false;
Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
}
}
} while (validInput == false);

Searching ObservableCollection's elements in a string

i am trying to search an observablecollection's items in a string.
I try as in the below code.
for (int j = 0; j < DBControl.Instance.SelectLanguagesFromDatabase().Count; j++)
{
if ( dominatorIntern.ProgrammingLanguages.Contains(ProgrammingLanguagesList[j] )
ProgrammingLanguagesList[j].IsSelected = true;
}
Here ProgrammingLanguagesList is an observablecollection, then i got an error saying
Error 8 Argument 1: cannot convert from
'InternRegistration.ViewModel.SelectionItem<string>' to 'string'
here, dominatorIntern.ProgrammingLanguages is a string storing languages like c,java,c++ and ProgrammingLanguagesList is an observablecollection.With an example
if ProgrammingLanguagesList ={c,java,c#} and dominatorIntern.ProgrammingLanguages=c,java i want to ProgrammingLanguagesList[0].IsSelected = true; and ProgrammingLanguagesList[1].IsSelected = true; how can i do that?
Based on your code... it looks like ProgrammingLanguagesList is an array of InternRegistration.ViewModel.SelectionItem<string>?
You need something like this...
// replace ??? on the next line with your SelectionItem<string>'s property that
// holds the language name.
var vmLanguageNameProp = ProgrammingLanguagesList[j].???
if ( dominatorIntern.ProgrammingLanguages.Contains(vmLanguageNameProp )
{
ProgrammingLanguagesList[j].IsSelected = true;
}
Also note that it looks like you are making a DB call for every loop iteration to get the count... you definitely don't want to do that if that is indeed what is going on there.

ArgumentNullException in an array that I can't figure out

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];
}

Categories