拆分多个数字

时间:2014-05-24 22:25:37

标签: c# input split numbers

我刚开始学习c#,我有点过头了。我试图让用户输入5个等级的列表,然后将它们拆分以计算最高,最低和平均值。

我不能使用int和split,但我不知道如何让它工作。

谢谢!

Console.WriteLine("Enter 5 Grades; Whole Integers Only, 0-100; One Space Between Grades");
int allgrades = int.Parse(Console.ReadLine());
string[] splitgrades = allgrades.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

g1.Name = name + "'s GradeBook";
Console.WriteLine(g1.Name);

Console.WriteLine("Press Any Key to Calculate Gradebook Statistics");
Console.ReadKey();

GradeBook book = new GradeBook();
book.AddGrade(splitgrades[0]);
book.AddGrade(splitgrades[1]);
book.AddGrade(splitgrades[2]);
book.AddGrade(splitgrades[3]);
book.AddGrade(splitgrades[4]);

谢谢大家的帮助;我改变了它

Console.WriteLine("Enter 5 Grades; Whole Integers Only, 0-100; One Space Between Grades");
        string[] splitgrades = Console.ReadLine().Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
        int grade = int.Parse(splitgrades[0]);
        int grade1 = int.Parse(splitgrades[1]);
        int grade2 = int.Parse(splitgrades[2]);
        int grade3 = int.Parse(splitgrades[3]);
        int grade4 = int.Parse(splitgrades[4]);

3 个答案:

答案 0 :(得分:0)

在第二行中,您尝试将整个输入解析为单个int。您希望先将string拆分为不同的int,然后再单独解析。

答案 1 :(得分:0)

您要求用户输入以空格分隔的整数列表,然后尝试将该字符串解析为单个整数。这会在运行时造成很多悲伤。相反,你想要这样的东西:

string allGrades = Console.ReadLine();
string[] splitGrades = allGrades.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

这将为您提供一系列(希望)5个整数等级,您可以添加到GradeBook。这样做是适当的时间来解析数组中各个字符串的整数。

// Use a foreach instead to allow the user to enter as many grades as they want.
for (int i = 0; i < 5; ++i)
    book.AddGrade(int.Parse(splitGrades[i]);

答案 2 :(得分:0)

拆分它,然后解析一个。

Console.WriteLine("Enter 5 Grades; Whole Integers Only, 0-100; One Space Between Grades");

string[] splitgrades = Console.ReadLine().Split();

g1.Name = name + "'s GradeBook";
Console.WriteLine(g1.Name);

Console.WriteLine("Press Any Key to Calculate Gradebook Statistics");
Console.ReadKey();

GradeBook book = new GradeBook();

book.AddGrade(Int32.Parse(splitgrades[0]));
book.AddGrade(Int32.Parse(splitgrades[1]));

等...