C#/WindowForm

ComboBox를 사용한 학점 계산기

hyun0229 2022. 4. 6. 11:08

디자인

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        TextBox[] titles;
        ComboBox[] crds;
       ComboBox[] grds;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txt1.Text = "인체의 구조와 기능I";
            txt2.Text = "일반수학I";
            txt3.Text = "창업개론";
            txt4.Text = "비주얼프로그래밍";
            txt5.Text = "기업과정신";
            txt6.Text = "중국어I";
            txt7.Text = "데이터사이언스";

            titles = new TextBox[7] { txt1, txt2, txt3, txt4, txt5, txt6, txt7 };
            crds = new ComboBox[7] { crd1, crd2, crd3, crd4, crd5, crd6, crd7 };
            grds = new ComboBox[7] { grd1, grd2, grd3, grd4, grd5, grd6, grd7 };

            int[] arrCredit = { 1, 2, 3, 4, 5, };
            List<string> lstGrade = new List<string>
            {
                "A+","A0","B+","B0","C+","C0","D+","D0","F"

            };
            foreach (var c in crds)
            {
                
             foreach(var i in arrCredit)       
                c.Items.Add(i);
               c.SelectedItem = 3;
            }
            foreach(var g in grds)
            {
                foreach (var c in lstGrade)
                    g.Items.Add(c);
            }
        }

        private void button_Click(object sender, EventArgs e)
        {
            double totalScore = 0;
            int totalCredits = 0;

            for(int i = 0; i < grds.Length; i++)
            {
                if(grds[i].SelectedItem != null) 
                {
                    int crd = int.Parse(crds[i].SelectedItem.ToString());
                    totalCredits += crd;
                    totalScore += crd * GetGrade(grds[i].SelectedItem.ToString());
                }
            }
            txtgrade.Text = (totalScore/totalCredits).ToString("0.00");
        }

        private double GetGrade(string v)
        {
            double grade;
            if(v=="A+")grade=4.5; //성적으로 학점 계산
            else if (v == "A0") grade = 4.0;
            else if (v == "B+") grade = 3.5;
            else if (v == "B0") grade = 3.0;
            else if (v == "C+") grade = 2.5;
            else if (v == "C0") grade = 2.0;
            else if (v == "D+") grade = 1.5;
            else if (v == "D0") grade = 1.0;
            else grade =0;
            return grade;
        }
    }
}

결과