[英]C# How do I use dictionaries and lists with user input?
我正在建立一个已经创建的项目。 这是我第一次使用字典/列表。 这是一个非常广泛的问题,因为我所著的书根本没有涵盖使用字典的问题,而且我很难找到具有在线用户输入的字典示例。 我编写了一个使用多维数组的程序,该程序向用户询问许多学生和许多考试,然后让用户输入每次考试的分数,并根据他们的考试分数输出每个学生的平均成绩。 我现在想实现同样的事情,只使用字典和列表而不是数组。 我什至不知道从哪里开始。 谁能解释这将如何工作? 这是我已经创建的代码,尽管它可能根本没有用:
class MainClass
{
public static void Main(string[] args)
{
int TotalStudents = 0;
int TotalGrades = 0;
Console.WriteLine("Enter the number of students: ");
TotalStudents = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the number of exams: ");
TotalGrades = Convert.ToInt32(Console.ReadLine());
int[,] scoresArray = new int[TotalStudents, TotalGrades];
for (int r = 0; r < TotalStudents; r++)
for (int c = 0; c < TotalGrades; c++)
{
Console.Write("Please enter exam score {0} for student {1}: ", c + 1, r + 1);
scoresArray[r, c] = Convert.ToInt32(Console.ReadLine());
}
for (int r = 0; r < scoresArray.GetLength(0); r++)
{
int studentSum = 0;
int testCount = 0;
for (int c = 0; c < scoresArray.GetLength(1); c++)
{
studentSum += scoresArray[r, c];
testCount++;
}
string gradeLetter = "";
double average = studentSum / testCount;
Console.WriteLine("\nStudent " + (r + 1).ToString() + " Average Score: " + average.ToString());
if (average >= 90)
{
gradeLetter = "A";
}
else if (average >= 80 && average < 90)
{
gradeLetter = "B";
}
else if (average >= 70 && average < 80)
{
gradeLetter = "C";
}
else if (average >= 60 && average < 70)
{
gradeLetter = "D";
}
else
{
gradeLetter = "F";
}
Console.WriteLine("Student " + (r + 1).ToString() + " will recieve a(n) " + gradeLetter + " in the class.\n");
}
Console.Write("\nPress the [ENTER] key to exit.");
Console.ReadLine();
}
}
字典是一个很棒的工具! 我尝试使用您的原始逻辑,但有时,我不得不另辟way径。 此外,我一直迷失于“ c”和“ r”索引变量。 我希望索引使用更长的名称。 希望这可以帮助。
//Let's create a gradeTranslator dictionary.
// As the grades follow the simple divisions along averages divisible by 10,
// we can just use the first digit of the average to determine the grade.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
bool useSampleData = true;
Dictionary<string, List<double>> gradeBook = new Dictionary<string, List<double>>();
Dictionary<int, string> gradeTranslator = new Dictionary<int, string>();
for (int i = 0; i < 6; i++) {
gradeTranslator.Add(i, "F");
}
gradeTranslator.Add(6, "D");
gradeTranslator.Add(7, "C");
gradeTranslator.Add(8, "B");
gradeTranslator.Add(9, "A");
gradeTranslator.Add(10, "A");
int TotalStudents, TotalGrades;
// For testing purposes, it is a lot easier to start with some
// sample data. So, I created a query to see if the user wants
// to use sample data or to provide her own input.
Console.WriteLine("Do you want to input the data (I) or allow me to use sample data (S)?");
var inputMethod = Console.ReadLine();
if(inputMethod.ToUpper().IndexOf("I") >=0) {
useSampleData = false;
}
// User Sample Data
if (useSampleData) { // test without using the console input
gradeBook.Add("Bob", new List<double>() { 67.8, 26.3, 33.2, 33.1, 67.2 });
gradeBook.Add("Dick", new List<double>() { 88.2, 45.2, 100.0, 89.2, 91.5 });
gradeBook.Add("Jane", new List<double>() { 99.2, 99.5, 93.9, 98.2, 15.0 });
gradeBook.Add("Samantha", new List<double>() { 62, 89.5, 93.9, 98.2, 95.0 });
gradeBook.Add("Estefania", new List<double>() { 95.2, 92.5, 92.9, 98.2, 89 });
TotalStudents = gradeBook.Count();
TotalGrades = gradeBook["Bob"].Count();
TotalStudents = 5;
// user will provide their own data.
} else {
Console.WriteLine("Enter the number of students: ");
TotalStudents = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the number of exams: ");
TotalGrades = Convert.ToInt32(Console.ReadLine());
for (int studentId = 0; studentId < TotalStudents; studentId++) {
Console.Write("Please enter name of student {0}: ", studentId);
var name = Console.ReadLine();
gradeBook.Add(name, new List<double>());
for (int testId = 0; testId < TotalGrades; testId++) {
Console.Write("Please enter exam score {0} for " +
"student {1}: ", testId + 1, name);
gradeBook[name].
Add(Convert.ToDouble(Console.ReadLine()));
}
}
}
// Here we will divide the grade by 10 as an integer division to
// get just the first digit of the average and then translate
// to a letter grade.
foreach (var student in gradeBook) {
Console.WriteLine("Student " + student.Key +
" scored an average of " + student.Value.Average() + ". " +
student.Key + " will recieve a(n) " +
gradeTranslator[(int)(student.Value.Average() / 10)] +
" in the class.\n");
}
Console.Write("\nPress the [ENTER] key to exit.");
Console.ReadLine();
}
}
}
建立一个学生班来保存信息。
public class Student
{
public string ID
public List<double> TestScores {get;set;}
// in this case average only has a getter which calculates the average when needed.
public double Average
{
get
{
if(TestScores != null && TestScores.Count >0)
{
double ave = 0;
foreach(var x in TestScores)//basic average formula.
ave += x;
// using linq this could be reduced to "return TestScores.Average()"
return ave/TestScores.Count;
}
return 0; // can't divide by zero.
}
}
public Student(string id)
{
ID = id;
TestScores = new List<double>();
}
}
现在,您的词典集合可以保留信息。 为了让您入门,这里有几种访问数据的方法。 绝对不是全部。
在字典中添加元素:
Dictionary<string,Student> dict = new Dictionary<string,Student>();
Student stud = new Student("Jerry");
dict.Add(stud.ID,stud);
拉取信息:
string aveScore = dict["Jerry"].Average.ToString("#.00");
Console.Write(aveScore);
遍历字典:
foreach(var s in dict.Keys)
{
dict[s].TestScores.Add(50);
}
由于这是家庭作业,或者您正在尝试学习如何使用字典,因此我不会为您发布代码而向您指出正确的方向。
C#中的Dictionary
是键-值对的集合。 Key
必须是唯一的,而Value
不必是唯一的。 因此,如果您按以下方式定义字典:
Dictionary<int, int> dict = new Dictionary<int, int>();
这意味着您已经创建了一个对集合,其中Key
的类型为int
, Value
的类型也为int
。 因此,如果您在字典中添加几个项目,其内容将如下所示:
在index = 0
,您有一个Key=1
且Value=100
。 在index = 1
,您有一个Key=2
和Value=200
。
但是,字典的Value
不一定必须是单个值。 它也可以是一个Collection
(或一个类对象,甚至另一个字典)。
由于您的要求是列出每位学生的分数,并且词典Value
允许Collection
,因此使用词典确实是个好主意。 但是,我们应该使用哪种字典?
好吧,有很多选择。
一种方法是使用Dictionary<string, List<int>>
。 代表学生姓名(或ID)的string
,以及代表考试成绩的List<int>
。 所以;
Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
现在,您可以使用每个学生的分数填充该词典。 例如:
dict.Add("Arthur Dent", new List<int>() { 75, 54, 26 });
dict.Add("Zaphod Beeblebrox", new List<int>() { 12, 13, 7 });
dict.Add("Ford Prefect", new List<int>() { 99, 89, 69 });
对于您的情况,您可以从用户那里获得每个学生的姓名和分数的输入。
但是,就像我说的那样,您也可以将类对象用作字典Value
,实际上,这是解决问题的更好方法。 Felix的答案显示了如何执行此操作,因此我将不赘述。 但实际上,您要按照以下步骤创建字典,假设您的班级是Student
。
Dictionary<string, Student> dict = new Dictionary<string, Student>();
然后根据用户输入创建Student
实例,并将其添加到字典中。 使用Student
类的另一个好处是,您可以将一个学生的所有相关信息放在一个地方,并且还可以使用其他辅助方法,例如Felix示例中的Average()
方法,因此您的代码将更加简洁明了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.