I'm having trouble with an IndexOf returning the position in a array
I looked online and wasn't able to find a solution so any help would be appreciated.
25 Replies
so which line is the culprit, what did you expect and what was actually happening?
line 36. I was expecting it to find the position of the name entered, return the value and then print the friend's details.
You have a
Friend[]
but you are actually searching with a string
This method would only work if Nombre
was a Friend
That's right.
For instance, on the initial prompt to enter friend details into the array, I include "John".
Later, I would be prompted again to find the birthday of the friend I want. If I type in "John" it should return the array position of that friend.
The program is not doing that.
Yeah, I know
Does it have to be
LastIndexOf
specifically?No.
Anything that works would be fine with me lol
Multiple ways to do it:
- loop through the friends and just do some if-magic
- use
System.Linq
and directly obtain the Friend
with Friend? f = friends.LastOrDefault(f => f.Name == Nombre);
. Instead of checking for the index, you can check f is null
We haven't been taught how to use linq yet so it'll have to be a loop.
Aight. Encapsulate it into a function then 😉
Sorry I don't follow.
You have a function
GetFriendData()
This function encapsulates logic to obtain data and create a Friend
object
Makes it reusable and more readable
Now do the same with "loop through my friend array and check if the name of the current friend is the name the user provided"
Or well... you dont have to do it, but it looks nicer + has the aforementioned benefitsCreating a function to loop through the array returned the same result.
I must be missing something.
How did you loop through your array?
Also, can you provide the name you are providing for the data and for the search?
Actually, I have another question, would a Array.IndexOf() even work in this context?
Array.IndexOf Methode (System)
Sucht das angegebene Objekt und gibt den Index seines ersten Auftretens in einem eindimensionalen Array oder in einem Elementbereich im Array zurück.
As you can see
expects an
object?
as second parameter. The function would try to match any element of the array with that object
But since you are providing a string, it'd try to compare Friend
objects with a stringIf the Friend objects aren't string values, then what are they?
They are
Friend
objects
Friends are Friends and strings are strings
But your Friend object contains a property that is a string Name
I understand what you mean but if the user input is a string data type how do I covert it to a Friend data type?
You don't. Your idea is the other way around. You don't convert a string to a Friend. All you need to do is to take a Friends
Name
property and compare this to the user input. Both are strings, so they can be comparedare my eyes deceiving me, or are your sub routines all in Main?
they are indeed local functions declared inside Main.
thats painful