gpt4 book ai didi

C# 如何使这段代码更紧凑 (If,else if,else)

转载 作者:行者123 更新时间:2023-11-30 19:54:47 25 4
gpt4 key购买 nike

我是一年级学生,我们被要求做作业,我想知道有没有其他方法可以检查用户输入,这样我就不必在每次输入后做所有的 if 和 else,或者有什么方法可以循环它并保存 6 个不同的答案或类似的东西.....

    static void Main(string[] args)
{
//var
string s0, s1, s2, s3, s4, s5; //subejects
string g0, g1, g2, g3, g4, g5;//grades

//input grades/subject
Console.Write("Enter Subject 1 : ");
s0 = Console.ReadLine();
Console.Write("Enter Grade 1 : ");
g0 = Console.ReadLine();
g0 = g0.ToUpperInvariant();
if (g0 == "H1")
g0 = "100";
else if (g0 == "H2")
g0 = "88";
else if (g0 == "H3")
g0 = "77";
else if (g0 == "H4")
g0 = "66";
else if (g0 == "H5" || g0 == "O1")
g0 = "56";
else if (g0 == "H6" || g0 == "O2")
g0 = "46";
else if (g0 == "H7" || g0 == "O3")
g0 = "37";
else if (g0 == "H8")
g0 = "0";
else if (g0 == "O4")
g0 = "28";
else if (g0 == "O5")
g0 = "20";
else if (g0 == "O6")
g0 = "12";
else if (g0 == "O7" || g0 == "O8")
g0 = "0";
else
Console.WriteLine("Wrong Grade Format!");

Console.Write("\nEnter Subject 2 : ");
s1 = Console.ReadLine();
Console.Write("Enter Grade 2 : ");
g1 = Console.ReadLine();
g1 = g1.ToUpperInvariant();

Console.Write("\nEnter Subject 3 : ");
s2 = Console.ReadLine();
Console.Write("Enter Grade 3 : ");
g2 = Console.ReadLine();
g2 = g2.ToUpperInvariant();

Console.Write("\nEnter Subject 4 : ");
s3 = Console.ReadLine();
Console.Write("Enter Grade 4 : ");
g3 = Console.ReadLine();
g3 = g3.ToUpperInvariant();

Console.Write("\nEnter Subject 5 : ");
s4 = Console.ReadLine();
Console.Write("Enter Grade 5 : ");
g4 = Console.ReadLine();
g4 = g4.ToUpperInvariant();

Console.Write("\nEnter Subject 6 : ");
s5 = Console.ReadLine();
Console.Write("Enter Grade 6 : ");
g5 = Console.ReadLine();
g5 = g5.ToUpperInvariant();

Console.Clear();

//collect information into array
for (int i = 0; i <= 5; i++)
{
string[] subjects = { s0, s1, s2, s3, s4, s5 };
string[] grades = { g0, g1, g2, g3, g4, g5 };

Console.WriteLine("{0,15}:{1,-15}", subjects[i],grades[i]);//output
}
}
}

如果我问的是愚蠢简单的问题,请不要生气,但我在网络上所能找到的只是更高级的方法....谢谢。

最佳答案

我建议像这样初始化一个字典来进行查找:

var lookup = new Dictionary<string, string>
{
["H1"] = "100",
["H2"] = "88",
["H3"] = "77"
// Etc.
};

然后查找字符串如下:

g0 = g0.ToUpperInvariant();

if (!lookup.TryGetValue(g0, out g0))
Console.WriteLine("Wrong Grade Format!");

关于C# 如何使这段代码更紧凑 (If,else if,else),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40721710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com