在具有未知对象的数组中查找对象的索引

时间:2018-04-18 12:30:34

标签: c#

在一个询问10名学生的姓名和年龄的程序中,最后我们必须输入其中一个的名称,程序必须在数组中给出它们的位置。它总是告诉我这个地方是0.这是代码:

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.");
    }       
}

编辑:谢谢大家的回答。我发现了IndexOutOfRange问​​题并轻松解决了。主要的问题是关于索引返回0.现在,在我把它放在循环上再次搜索数组之后,它为第一个名称返回0,为第二个名称返回1,依此类推。这是正确的方法,还是应该为第一个名称返回1,为第二个名称返回2等?

4 个答案:

答案 0 :(得分:3)

在循环结束时i的值为10。 (这就是取消条件:i < 10变为true并且循环退出的原因。)

因此,当您尝试在循环之后访问a[i]时,它将抛出IndexOutOfRange异常。因为你的数组中没有足够的元素。

解决方案:要查找需要在数组中循环 的元素,并将每个值与搜索名称进行比较:

 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.");

编辑:当然可能存在搜索名不在列表中的情况。您可以通过使用index初始化-1值并在搜索循环后检查它来处理此类情况:

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!");
}

答案 1 :(得分:2)

您发布的此代码无效,因为它会引发异常System.IndexOutOfRangeException

然而,除了这个例外,我的回答是: 监守,

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

通过执行此操作,您正在检查数组的第i个条目是否是您想要的条目,如果是,那么您将使用i设置索引。

但它不匹配呢? index将保留其初始化时的值。这里输出的结果为零。

你应该像下面这样做。

             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");

答案 2 :(得分:1)

考虑创建一个包含所有学生特定数据的Student对象:

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

现在创建一个Student的列表:

var students = new List<Student>();

在循环中为每次重复创建一个新的Student对象:

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

在循环之后,您要求索引的学生姓名,并使用LINQ在列表中找到他:

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");
}


查看C#的string interpolation功能,了解如何使用变量构建字符串。我觉得它更清洁。

答案 3 :(得分:0)

索引始终为0,因为您的class AdminMaintenanceController extends AdminMaintenanceControllerCore { public function __construct() { $this->bootstrap = true; $this->className = 'Configuration'; $this->table = 'configuration'; parent::__construct(); $this->fields_options = array( 'general' => array( 'title' => $this->l('General'), 'fields' => array( 'PS_SHOP_ENABLE' => array( 'title' => $this->l('Enable Shop'), 'desc' => $this->l('Activate or deactivate your shop (It is a good idea to deactivate your shop while you perform maintenance. Please note that the webservice will not be disabled).'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool' ), 'PS_MAINTENANCE_IP' => array( 'title' => $this->l('Maintenance IP'), 'hint' => $this->l('IP addresses allowed to access the front office even if the shop is disabled. Please use a comma to separate them (e.g. 42.24.4.2,127.0.0.1,99.98.97.96)'), 'validation' => 'isGenericName', 'type' => 'maintenance_ip', 'default' => '' ), ), 'submit' => array('title' => $this->l('Save')) ), 'image' => array( 'title' => $this->l('Images parameters'), 'fields' => array( 'PS_IMG1' => array( 'title' => $this->l('Left side image'), 'type' => 'file', 'name' => 'PS_IMG1', 'thumb' => _PS_IMG_.'PS_IMG1.jpg', 'hint' => $this->l('Choose the photo for this side'), ), ), 'submit' => array('title' => $this->l('Save')) ), 语句不在lopp中。所以你实际上并没有在数组中搜索,只检查它是否像第11个(数组开始计数为0)元素。 (在你的for循环之后我被设置为10)