我在上一篇文章中使用了相同的代碼,但現在我正在嘗試除錯錯誤,例如
System.ArgumentNullException: 'Value cannot be null. (Parameter 'values')'
當我做
static void Main(string[] arg){
int[] numbers = new int[] { 2, 4 };
Console.WriteLine(String.Join(",", HowSum(7, numbers)));
}
HowSum()回傳 NULL時如何解決此問題?
以下是原帖供參考:
class HowSumSlow {
static int[] HowSum(int targetSum, int[] numbers)
{
int[] empty = new int[] { };
if (targetSum == 0) return empty;
if (targetSum < 0) return null;
foreach( var num in numbers){
var remainder = targetSum - num;
int[] remainderResult = HowSum(remainder, numbers);
if (remainderResult != null){
return remainderResult.Append(num).ToArray();
}
}
return null;
}
static void Main(string[] arg) {
int[] numbers = new int[] { 2, 3, 5 };
Console.WriteLine(String.Join(",", HowSum(8, numbers)));
}
}
uj5u.com熱心網友回復:
當 HowSum() 回傳 NULL 時,我該如何解決這個問題?
您可以使用??來指定null陣列的后備:
Console.WriteLine(String.Join(",", HowSum(7, numbers) ?? Array.Empty<int>()));
現在您將一個空的 int 陣列傳遞給String.Joinif HowSumreturns null。
uj5u.com熱心網友回復:
只需進行常規 null 檢查以查找函式是否回傳 null
if (HowSum(8 , numbers) != null) {
Console.WriteLine(String.Join(",", HowSum(8, numbers)));
} else {
Console.WriteLine("ITS NULLLLL");
}
希望它有所幫助。:)
uj5u.com熱心網友回復:
在我之前的回答(此后已洗掉)中,我錯過了遞回。因此,您需要null回傳停止標準。
因此,負值是遞回時的有效輸入,但不是targetSum起始值。
所以,你可以做的是給它一個“入門方法”——像這樣:
// Your "HowSum" Method stays untouched!
static int[] StartHowSum(int targetSum, int[] numbers)
{
if (targetSum < 0)
{
throw new ArgumentOutOfRangeException (
nameof(targetSum), targetSum,
"Argument must be greater than or equal to 0."
);
}
if (targetSum == 0) return Array.Empty<int>();
// maybe also sanity-check `numbers`?
int[] result = HowSum(targetSum, numbers);
// Now that we checked input, is it possible to still get null OUTput?
return result ?? Array.Empty<int>();
}
static void Main(string[] arg) {
int[] numbers = new int[] { 2, 3, 5 };
Console.WriteLine(String.Join(",", StartHowSum(8, numbers)));
}
uj5u.com熱心網友回復:
在考慮了大家所說的之后,我發現最簡單的方法是只存盤結果并使用 ?-operator。(謝謝大家。我想在每條評論中都寫下,但顯然我應該避免這樣做。)
這是最終的代碼。
static int[] HowSum(int targetSum, int[] numbers)
{
int[] empty = new int[0];
if (targetSum == 0) return Array.Empty<int>();
if (targetSum < 0) return null;
foreach (var num in numbers)
{
var remainder = targetSum - num;
int[] remainderResult = HowSum(remainder, numbers);
if (remainderResult != null){
return remainderResult.Append(num).ToArray();
}
}
return null;
}
static void Main(string[] arg)
{
int[] numbers = new int[] { 2, 4 };
int[] result = HowSum(7, numbers);
Console.WriteLine(result == null ? "null" : String.Join(",", result));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/436230.html
上一篇:我無法用給定的變數創建圖
