一般来说,我知道int32
错误意味着没有为控制台程序转换字符串值。我已经看到很多代码试图找到这个问题的答案,包括以下 stackoverflow 问题(见得多,但这些是最有用的:
话虽如此,这也是一项家庭作业,标题为 UsingSum.cs,如其中几个链接所示。我和这些的不同之处在于我试图让用户输入他们想要的任何整数,然后将它们相加。整个作业写在链接2中......
问题:尽管我做出了改变,但我总是得到 0 或System.Int32[]
而不是总和。
我不能使用 Linq。
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UsingSum
{
class Program
{
static void Main(string[] args)
{
int i;
int usrInput;
bool running = true;
//Enter Question Asking Loop w/ running=true
while (running)
{
Console.Write("Enter a number or enter 999 to exit: ");
int[] array1 = new int[0];
for (i = 0; i < array1.Length; i++)
{
usrInput = Convert.ToInt32(Console.ReadLine());
array1[i] = Convert.ToInt32(usrInput);
}
for (i = 0; i < array1.Length; i++)
{
Console.WriteLine(array1[i]);
}
/*If the user enters 999, calls Sum() and asks user to press any key to exit.
changes 'running' from true to false to exit the question loop*/
int exit = Convert.ToInt32 (Console.ReadLine());
if (exit == 999)
{
running = false;
Sum(array1);
}
}
//Loop complete
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
public static void Sum(int[] numbers)
{
int [] sum1 = new int [0];
int sum2 = 0;
//Program accepts user responses with or w/o this loop...Int.32 error present both ways
//for (int a = 0; a < numbers.Length; ++a)
//sum1[a] = a;
//additional loop tried w/o the loop above/below;
//when used in the WriteLine w/ sum2 it displays 0, when used with sum1 or numbers Int.32 error
//Array.ForEach(sum1, delegate(int i) { sum2 += i; });
foreach (int i in numbers)
sum2 =+ i;
Console.WriteLine("The sum of the values in your array is: " + sum1);
/*tried changing 'numbers' to sum1, sum2, sum1.Convert.ToString(),sum2.Convert.ToString()
numbers.Convert.ToString(), also tried converting sum2 to a string.*/
}
}
}
这是我的最终解决方案!
static void Main(string[] args)
{
AskUserForNumbers();
Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
public static List<Int32> AskUserForNumbers()
{
bool running = true;
List<int> numbers = new List<int>();
while (running)
{
Console.Write("Enter a number or enter 999 to exit: ");
int inputValue;
var inputString = Console.ReadLine();
//Check for "999" which indicates we should display the numbers entered, the total and then exit our loop.
if (inputString == "999")
{
Console.WriteLine("The sum of the values in your array is: " + numbers.Sum());
running = false;
}
else if (Int32.TryParse(inputString, out inputValue) && inputValue > 0)
{
numbers.Add(inputValue);
}
else
{
Console.WriteLine("Please enter a whole number greater than 0");
}
}
return numbers;
}
}
}