Skip to main content
 首页 » 编程设计

c#之索引越界异常控制台应用程序

2024年02月13日16dflying

我不明白的是那一行:

 Class exmp 
 { 
    Static void Main(String userinput) 
    { 
       Int input = int.parse(userinput[0]); 
    } 
 } 

显然没有方法接受参数,所以这可能是执行的原因 我是新手,求助

请您参考如下方法:

userinput[0] 是字符串的第一个字符。因此对于空字符串,没有第一个字符,因此:Index out of bounds

如果您想防止这种情况发生,您可以执行以下操作:

 Class exmp 
 { 
    Static void Main(String userinput) 
    { 
      Int input = 0; 
      if( userinput.length > 0 ) 
      { 
        int.TryParse(userinput[0], out input); 
      } 
    } 
 } 

如果传入空字符串,这会将 input 设置为 0。

因此对于输入 '532632fergerg' input 将是 '5' 对于输入 'fwehgwerhwh' 它将爆炸,因为 'f' 不是字符串。在这种情况下,您可能希望使用 TryParse 而不是 Parse。

编辑 更新我的代码以使用 TryParse,因为它更可靠,尤其是在处理您不知道是什么的用户输入时。