
C#中如何解决"索引超出了数组界限"这个异常
classlistArg0{publicstaticvoidMain(String[]args){stringstrName;//声明一个string类型的值变量strN...
class listArg0
{
public static void Main(String[] args)
{
string strName; //声明一个string类型的值变量
strName = args[0]; //把第一个参数赋给变量strName
Console.WriteLine("This is the first argument: {0}!", strName); //格式化输出第一个参数
}
}
这个程序可以成功生成,但运行的时候显示说"未处理的异常:System.IndexOutOfRangeException:索引超出了数组界限"?
小弟不明白,请各位高手指点!万分感谢! 展开
{
public static void Main(String[] args)
{
string strName; //声明一个string类型的值变量
strName = args[0]; //把第一个参数赋给变量strName
Console.WriteLine("This is the first argument: {0}!", strName); //格式化输出第一个参数
}
}
这个程序可以成功生成,但运行的时候显示说"未处理的异常:System.IndexOutOfRangeException:索引超出了数组界限"?
小弟不明白,请各位高手指点!万分感谢! 展开
5个回答
展开全部
"索引超出了数组界限"并不是说索引有多长,
而是说这个索引在数组的界限当中找不到,
在楼主的代码中,
无法保证String[] args 一定有值(即可能不存在args[0]),
如果楼主是想在string[] args有值的情况下才输出第一个参数的话,
可以改成
class Program
{
static void Main(string[] args)
{
string strName; //声明一个string类型的值变量
if (args.Count() > 0)
{
strName = args[0];//把第一个参数赋给变量strName
Console.WriteLine("This is the first argument: {0}!", strName); //格式化输出第一个参数
}
}
}
如果楼主想不管有没有值都输出信息,
可以改成:
static void Main(string[] args)
{
string strName = "args is null"; //声明一个string类型的值变量(当数组string[] args 没值时,输出args is null)
if (args.Count() > 0)
{
strName = args[0];//把第一个参数赋给变量strName
}
Console.WriteLine("This is the first argument: {0}!", strName); //格式化输出第一个参数
}
而是说这个索引在数组的界限当中找不到,
在楼主的代码中,
无法保证String[] args 一定有值(即可能不存在args[0]),
如果楼主是想在string[] args有值的情况下才输出第一个参数的话,
可以改成
class Program
{
static void Main(string[] args)
{
string strName; //声明一个string类型的值变量
if (args.Count() > 0)
{
strName = args[0];//把第一个参数赋给变量strName
Console.WriteLine("This is the first argument: {0}!", strName); //格式化输出第一个参数
}
}
}
如果楼主想不管有没有值都输出信息,
可以改成:
static void Main(string[] args)
{
string strName = "args is null"; //声明一个string类型的值变量(当数组string[] args 没值时,输出args is null)
if (args.Count() > 0)
{
strName = args[0];//把第一个参数赋给变量strName
}
Console.WriteLine("This is the first argument: {0}!", strName); //格式化输出第一个参数
}
展开全部
主函数运行的时候,你都没有带参数,哪args[0]就没有获得值。当然超出数组界限啦
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
最上面缺了个分号;
你那个数组没给初值呀。 所以出错。
你那个数组没给初值呀。 所以出错。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
for循环里面的循环次数多了一次应该
i
<=
scores.Length-1
for
(int
i
=
0;
i
<=
scores.Length-1;
i++)
i
<=
scores.Length-1
for
(int
i
=
0;
i
<=
scores.Length-1;
i++)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
我想难道是变量值很长,你试试用StringBuilder
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询