我是编程新手。现在,我必须学习C#列表项。
我的期望:
我的程序:
using System;
using System.Collections.Generic;
namespace Indexof_in_List
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Implementation of IndexOf Method with List");
Console.WriteLine();
//If the user entered empty value or nothing in the console window, the window will exit automatically
//Create an Empty List
List<int> name = new List<int>();
Console.WriteLine("Enter the Input values for the List");
//Get the Inputs for the List from the Console Window
for (int n = 0; n < name.Count; n++)
{
bool check;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name[n] = val;
}
else
{
Environment.Exit(0);
}
}
//Implement Index of any number in the list items which you have entered to the console
Console.WriteLine("The Index of value 10 is = {0}",name.IndexOf(10));
Console.WriteLine();
Console.WriteLine("The Index of value 1000 is ={0}", name.IndexOf(1000));
Console.WriteLine();
Console.ReadKey();
}
}
}
有人可以告诉我此C#逻辑的解决方案吗?还告诉我这次失败的原因吗?
告诉我,我的逻辑是否正确?
答案 0 :(得分:1)
您的代码有几个问题:
Count
检索列表中的当前项目数。Capacity
也为0。因此,您不能从0循环到name.Capacity
。name[index]
语法访问现有项目。最简单的解决方案是按原样初始化列表,然后简单地添加项目:
List<int> name = new List<int>();
for (int i = 0; i < 10; ++i)
{
bool check;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name.Add(val);
}
else
{
Environment.Exit(0);
}
}
这将依次读取10个数字并将它们添加到列表中。
答案 1 :(得分:0)
感谢您的宝贵意见。最后,根据您的反馈,我完成了最后的更改。
我的代码:
using System;
using System.Collections.Generic;
namespace Indexof_in_List
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Implementation of IndexOf Method with List");
Console.WriteLine();
//Create an Empty List
List<int> name = new List<int>();
//If the user entered empty value or nothing in the console window, the window will exit automatically
Console.WriteLine("Enter the Input values for the List");
//Get the Inputs for the List from the Console Window
for (int n=0;n<5;n++)
{
bool check=false;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name.Add(val) ;
}
else
{
Environment.Exit(0);
}
}
if (name.Count != 0)
{
//Implement Index of any number in the list items which you have entered to the console
int index1 = name.IndexOf(10);
Console.WriteLine("The Index of value 10 is = {0}", name.IndexOf(10));
if (index1!=-1)
{
Console.WriteLine("The number 10 found in the List");
}
else
{
Console.WriteLine("The Number 10 found in the List");
}
int index2 = name.IndexOf(1000);
Console.WriteLine("The Index of value 1000 is ={0}", name.IndexOf(1000));
if (index2 != -1)
{
Console.WriteLine("The number 1000 found in the List");
}
else
{
Console.WriteLine("The Number 1000 not found in the List");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}