Sts013
Sts013

Reputation: 3

Find the index of an object in an array with unknown objects

In a program that asks the name, surname and age of 10 student, at the end we have to enter the name of one of them and the program has to give their place in the array. It always tells me that the place is 0. Here is the code:

public class Program_pinakes
{
    public static void Main(string[] args)
    {
        int i; 
        string[] a = new string[10]; 
        string[] b = new string[10]; 
        int[] c = new int[10]; 
        int index = 0;

        for (i = 0; i < 10; i++)
        {  
            Console.Write("Name: ");
            a[i] = Console.ReadLine();
            Console.Write("Surname: ");
            b[i] = Console.ReadLine();
            Console.Write("Age: ");
            c[i] = Int32.Parse(Console.ReadLine());
        }

        Console.Write("Name of student you are looking for: ");
        string name = Console.ReadLine();
        if (name == a[i])
            index = i;

        Console.Write("Student"+a[i]+" is located at"+index+" place.");
    }       
}

Edit: Thank you all for your answers. I found out about the IndexOutOfRange problem and solved it easily. The main problem was about the index returning 0. Now, after I put it on the loop to search the array again, it returns 0 for the first name, 1 for the second and so on. Is this the right way, or it should be returning 1 for the first name, 2 for second etc?

Upvotes: 0

Views: 700

Answers (4)

Mong Zhu
Mong Zhu

Reputation: 23732

At the end of the loop i has the value of 10. (This is the reason why the cancel condition: i < 10 becomes true and the loop exits).

So when you try to access a[i] after the loop it will throw an IndexOutOfRange exception. Because you have not enough elements in your array.

Solution: To find an element you need to loop again through the array and compare each value with the search-name:

 for(int i = 0; i < 10; i++ )
 {
    if (name == a[i])
    {
       index = i;
       break; // finish the loop, you have found the first occurence
    }
 }
 Console.Write("The first occurence of Student: "+name+" is located at"+index+" place.");

Edit: There can be a case of course that the search-name is not in the list. You can handle such a case by initializing the index value with -1 and check for it after the search loop:

int index = -1;

// search loop here

if (index > -1)
{
    Console.Write("The first occurence of Student: " + name + " is located at" + index + " place.");
}
else
{
    Console.Write("Student: "+ name +" could not be found!");
}

Upvotes: 3

Amit
Amit

Reputation: 1857

This code you have posted is not working, as it will throw an exception System.IndexOutOfRangeException.

However apart from this exeption, my answer would be: becuase,

       if (name == a[i])
            index = i;
         Console.Write("Student"+a[i]+" is located at"+index+" place.");

by doing this you are checking if ith entry of the array is the one you desired or not, if yes then you are setting index with i.

But what about it doesn't match? index will stay with the value as it was initialized with. Here it is zero what you are getting in output.

you should be doing like below.

             index = -1;
             for(int j = 0; i < a.Length; j++ )
             {
                if (name == a[j])
                {
                   index = j;
                   break;
                }
             }
             if(index != -1)
                Console.Write("Student" + name + " is located at" + (index + 1) + " place.");
             else
               Console.Write("Student" + name + " is not in list");

Upvotes: 2

croxy
croxy

Reputation: 4168

Consider creating a Student object which holds all your student specific data:

class Student
{
   public string Name { get; set; }
   public string Surename { get; set; }
   public int Age { get; set; }
}

Now create a list of Student:

var students = new List<Student>();

And in your loop create a new Student object for every repetition:

for (i = 0; i < 10; i++)
{  
   Console.Write("Name: ");
   var name = Console.ReadLine();
   Console.Write("Surname: ");
   var surname = Console.ReadLine();
   Console.Write("Age: ");
   var age = Int32.Parse(Console.ReadLine());

   students.Add(new Student {Name = name, Surname = surname, Age = age});
}

After the loop you ask for the name of the student you want the index for and use LINQ to find him in the list:

Console.Write("Name of student you are looking for: ");
string name = Console.ReadLine();
var foundStudent = students.FirstOrDefault(s => s.Name.Equals(name));
if(foundStudent != null)
{
   var index = students.IndexOf(foundStudent);
   Console.Write($"Student {foundStudent.Name} is located at {index} place.");
}
else
{
   Console.WriteLine($"No student for name {name} found");
}

NOTE:
Check out C#'s string interpolation feature for building strings with variables. I find it way more cleaner.

Upvotes: 1

misanthrop
misanthrop

Reputation: 939

The index always is 0 because your if (name == a[i]) statement is not in a lopp. So you do not actually search in the array but only check if it is like the 11th (array starts to count at 0) element. (i is set to 10 after your for loop)

Upvotes: 0

Related Questions