OneBigLoser
OneBigLoser
发布于 2024-06-23 / 15 阅读
0
0

C# 异常捕获练习题 中等难度

#C#

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("请输入学生的姓名:");
        string name = Console.ReadLine();

        int chineseScore = GetValidScore("语文");
        int mathScore = GetValidScore("数学");
        int englishScore = GetValidScore("英语");

        Console.WriteLine("\n学生信息:");
        Console.WriteLine("姓名: " + name);
        Console.WriteLine("语文成绩: " + chineseScore);
        Console.WriteLine("数学成绩: " + mathScore);
        Console.WriteLine("英语成绩: " + englishScore);
    }

    private static int GetValidScore(string subject)
    {
        int score;
        while (true)
        {
            Console.WriteLine("请输入" + subject + "成绩 (0-100):");
            string input = Console.ReadLine();

            // 尝试将输入转换为整数
            if (int.TryParse(input, out score) && score >= 0 && score <= 100)
            {
                break; // 输入合法,跳出循环
            }
            else
            {
                Console.WriteLine("输入错误,请输入一个介于0到100之间的整数。");
            }
        }

        return score;
    }
}


评论