HackerRank aVeryBigSum报错:System.ArgumentNullException(path为空)求助
HackerRank aVeryBigSum 报错问题解析
1. System.ArgumentNullException 报错原因
这个报错的直接原因是创建StreamWriter时传入的path参数为null。你的代码中:
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
System.Environment.GetEnvironmentVariable("OUTPUT_PATH")没有获取到有效路径值,返回了null,而StreamWriter的构造函数不允许path参数为null,因此触发了该异常。
这个报错确实和TextWriter相关——StreamWriter是TextWriter的子类,初始化它时必须提供合法的输出路径。
2. 数组索引越界问题
你的求和函数中循环条件i<=ar.Count存在错误:List的索引范围是0到ar.Count-1,当i等于ar.Count时,ar[i]会访问不存在的元素,导致索引越界异常。需要将循环条件修改为i<ar.Count。
修正后的完整代码
using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Text; using System; class Result { /* * Complete the 'aVeryBigSum' function below. * * The function is expected to return a LONG_INTEGER. * The function accepts LONG_INTEGER_ARRAY ar as parameter. */ public static long aVeryBigSum(List<long> ar) { long sum = 0; // 修正循环条件,避免索引越界 for (int i = 0; i < ar.Count; i++) { sum += ar[i]; } return sum; } } class Solution { public static void Main(string[] args) { // 处理OUTPUT_PATH为空的情况,本地测试可直接用Console.Out string outputPath = System.Environment.GetEnvironmentVariable("OUTPUT_PATH"); TextWriter textWriter = string.IsNullOrEmpty(outputPath) ? Console.Out : new StreamWriter(outputPath, true); int arCount = Convert.ToInt32(Console.ReadLine().Trim()); List<long> ar = Console.ReadLine().TrimEnd().Split(' ') .Select(arTemp => Convert.ToInt64(arTemp)) .ToList(); long result = Result.aVeryBigSum(ar); textWriter.WriteLine(result); textWriter.Flush(); textWriter.Close(); } }
补充说明
本地测试时,如果OUTPUT_PATH环境变量未设置,可直接用Console.Out替代StreamWriter,避免路径为空的问题;在HackerRank平台上,该环境变量会自动配置,无需额外处理。
内容的提问来源于stack exchange,提问作者SonerB
相关产品推荐
相关产品推荐

