简体   繁体   中英

C# How can I make this code better or shorter?

so I basically just started learning computer programming (C#), and today I got to learn about Arrays . I kinda, sorta, understand what Arrays are , I know they are used for a way of keeping track of a list or collection of many related things all together. So I was thinking of making a program which asks the user for his name and after you put your name it would automatically give you the score that you got on "the test" so I wanna show you guys my code and I'll love some feedback on how can I make my code look better and shorter I guess.. anyways here's my code.

        string studentNumberOne = "Miguel"; 
        string studentNumberTwo = "Maddie";
        string studentNumberThree = "John";
        string studentName = ""; // Empty string variable for user input...


        int[] grades = new int[3] { 90, 85, 70 }; // arrays, grades for each students...

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        studentName = Convert.ToString(Console.ReadLine()); //


        if (studentName == studentNumberOne) 
        {
            Console.WriteLine(studentNumberOne + " your score was " + grades[0]);

        }

        else if (studentName == studentNumberTwo)
        {
            Console.WriteLine(studentNumberTwo + " your score was " + grades[1]);

        }

        else if (studentName == studentNumberThree)
        {
            Console.WriteLine(studentNumberThree +" your score was " + grades[2]);
        }



    }
}

I know there's a lot of if/else if's and that's why I'm asking for some feedback on how I can make this code better or shorter, I'm pretty sure there has to be a way with Arrays where you can store all three names that I have in my code and also give them their correspondent score, so yeah, I'll love the feedback, thank you! Also try to not go with crazy answer or too much details I guess, like I said I just started learning C# so try to make it as simple as possible so I can understand better (If you can or want).

PD : Sorry for my bad grammar, English is not my first language.

You can create a class representing the student information such as Name and Grades. Have student information stored in a list of student objects. Use LINQ to filter the list based on the student name.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<Student> students = new List<Student>
        {
            new Student {Name = "Miguel", Grades = 90},
            new Student {Name = "Maddie", Grades = 70},
            new Student {Name = "John", Grades = 65},
            new Student {Name = "Isabella", Grades = 80},
            new Student {Name = "Raul", Grades = 75}
        };

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        string studentName = Console.ReadLine(); //

        var student = students.FirstOrDefault(std => std.Name == studentName);
        if (student != null)
        {
            Console.WriteLine(studentName + " your score was " + student.Grades);
        }
    }
}

public class Student
{
    public string Name { get; set; }

    public int Grades { get; set; }
}

The general rule is to never copy and paste similar code over and over again . This is the reason arrays and loops exist. Put the students in an array and look through them to find a match

class Program
{
    static void Main(string[] args)
    {
        string[] students=new string[] {
            "Miguel", "Maddie", "John", "Isabella", "Raul" };

        int[] grades=new int[] { 
            90, 85, 70, 92, 87 }; // arrays, grades for each students...

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        string studentName=Console.ReadLine(); //

        for (int i=0; i<students.Length; i++)
        {
            if (students[i].Equals(studentName))
            {
                Console.WriteLine(studentName+" your score was "+grades[i].ToString());
            }
        }

    }
}

Edit 1

OF course the CRL has a Dictionary object for connecting for example names to grades. This is far more efficient and flexible than maintain two separate arrays. See example below:

    static void Main(string[] args)
    {
        Dictionary<string, int> grades=new Dictionary<string, int>();
        grades["Miguel"] = 90;
        grades["Maddie"] = 85;
        grades["John"] = 70;
        grades["Isabella"] = 92;
        grades["Raul"] = 87;

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        string studentName=Console.ReadLine(); //

        if (grades.ContainsKey(studentName))
        {
            Console.WriteLine(studentName+" your score was "+grades[studentName]);
        }
    }

You can try this one.

using System;
using System.Collections.Generic;
class Program
{
    static void Main(string[] args)
    {
        List<string> students = new List<string> {
            "Miguel", "Maddie", "John", "Isabella", "Raul" };

        int[] grades=new int[] { 
            90, 85, 70, 92, 87 }; // arrays, grades for each students...

        Console.WriteLine("Please enter your name: "); // Asking the user to type his/her name
        string studentName=Console.ReadLine();
        try{
          Console.WriteLine(studentName+" your score was "+grades[students.IndexOf(studentName)].ToString());
          }
          catch(Exception){
            Console.WriteLine("name Not found");
          }
    }
}

You can change the exception to IndexOutOfRangeException if you need more accurate error tracking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM