C# second experiment: Object Oriented Programming

Posted by RyanW on Fri, 21 Jan 2022 13:02:16 +0100

Note: This article was created by me and copied from my other CSDN account (cancelled). Because the original doc file is lost, it is copied directly from the original tweet, so the picture may be watermarked.

Experiment 1

[Objective] to find the area of triangle

[experimental requirements]

The method of realizing the area of a triangle with at least four methods: method parameter array, interface, constructor, class inheritance and so on;

The simplest is based on the area of the rectangle = length × Width infers the area of the parallelogram = bottom × Because two identical triangles can form a parallelogram, the area calculation formula can be obtained:

Area of triangle = bottom × High ÷ 2 [S=ah ÷ 2]

Or:

Product of any two sides of a triangle × The sine of the included angle on both sides ÷ 2 [S=ab × sin × 1/2];

(method 1, [S=ah ÷ 2])

[experiment code]

using System;
namespace homework2_1
{
    //Define interface IPartOne
    public interface IPartOne       
    {
        void SetDataOne(string dataOne);        //Constructor
    }
    //The WritesthClass class derives from the IPartOne interface
    public class WritesthClass : IPartOne       
    {
        private string DataOne;
        //
        public void SetDataOne(string dataOne)
        {
            DataOne = dataOne;
            Console.WriteLine("{0}", DataOne);
        }
    }
    //Define abstract base class: Shape
    public abstract class Shape    
    {
        public Shape() {; }
    }
    //Definition of the Rectangular class. Circle is a subclass of Shape class;
    public class Rectangular: Shape     
    {
        //Length and Width are attributes of rectangle;
        protected double Length, Width;     
        public Rectangular ()
        {
            Length = 0; 
            Width = 0;      //Initialization of variables Length and Width;
        }

        public Rectangular (double Length,double Width)
        {
            this.Length = Length;
            this.Width = Width;
        }
        public double MianjiIs()
        {
            return Length * Width;
        }
    }
    public class Triangle:Rectangular       //The triangle class derives from the rectangle class
    {
        public Triangle (double Length,double Height)       //Method, with parameters, where is a formal parameter, and the parameters in the main function are arguments.
        {
            this.Length = Length;
            this.Width = Height;
        }    
        public double MianjiIs()
        {
            return 0.5* Length * Width;
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {          
            Console.WriteLine("Please enter the length of the bottom edge and height to enter the interval:");
            double i = Convert.ToInt32(Console.ReadLine());
            double j = Convert.ToInt32(Console.ReadLine());
            Triangle Tri = new Triangle(i, j);       //Instantiate and set the three sides of the triangle
            WritesthClass a = new WritesthClass();
            a.SetDataOne("Triangle area is:");
            Console.WriteLine("{0}", Tri.MianjiIs());
        }
    }
}

[operation results]
Set the bottom edge and height to 3 and 4 respectively, and the obtained area is: 6;

[experience]

When I first started writing this program, I had no bottom in my heart. Because I read the program before, and I designed and wrote a program myself for the first time. Therefore, in the parameter array of the method, the inheritance of the class and the use of the constructor, we draw lessons from example 3.3 in the book; In terms of interface, reference is made to example 2.28 in the book

In the polishing period of programming, I want to add a function of inputting triangle parameters, so there are still some references:

double i = Convert.ToInt32(Console.ReadLine());

When looking for input statements in the textbook, I found only string input statements, not numbers. So I checked on the Internet and got the sentence of converting string to number, and got satisfactory results.

After programming with the program in the book as the "script", an error is found:

Error CS0120 object reference is required for non static field, method or property 'Triangle.GetMianji()'

This mistake puzzled me. I checked a lot of data, but there was no answer in the end. After hard thinking, I finally understand my problem - there is no instantiation of one of the constructors in the main function.

After solving the problem, everything went well.

(method 2): [S=ab × sin × 1/2]
[experiment code]

using System;
namespace homework2_1
{
    //Define interface IPartOne
    public interface IPartOne
    {
        void SetDataOne(string dataOne);        //Constructor
    }
    //The WritesthClass class derives from the IPartOne interface
    public class WritesthClass : IPartOne
    {
        private string DataOne;
        //
        public void SetDataOne(string dataOne)
        {
            DataOne = dataOne;
            Console.WriteLine("{0}", DataOne);
        }
    }
    //Define abstract base class: Shape
    public class Shape
    {
        protected double Aside, Bside, Cside;
        public Shape() 
        {
            Aside= Bside= Cside=0; 
        }
        public Shape(double Aside, double Bside, double Cside)      //method
        {
            this.Aside = Aside;
            this.Bside = Bside;
            this.Cside = Cside;
        }
    };

    public class Triangle : Shape       //The triangle class is a subclass of the shape class
    {
        public Triangle(double Aside, double Bside,double Cside)       //Method has three parameters, which represent the three sides of the triangle, of which are formal parameters, and the parameters in the main function below are real parameters.
        {
            this.Aside = Aside;
            this.Bside = Bside;
            this.Cside = Cside;
        }
        public double MianjiIs()        //Constructor, calculating area
        {
            double CosB=(Aside* Aside+ Cside* Cside- Bside* Bside)/(2* Cside* Aside);
            double SinB= System.Math.Sqrt(1-CosB* CosB);
            return 0.5* Aside* Cside*SinB;
        }
    }
    class Program       //Program class, where the main program is implemented
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Please enter the length of the three sides to enter the interval:");
            double i = Convert.ToInt32(Console.ReadLine());
            double j = Convert.ToInt32(Console.ReadLine());
            double k = Convert.ToInt32(Console.ReadLine());
            Triangle Tri = new Triangle(i, j, k);       //Instantiate and set the three sides of the triangle
            WritesthClass a = new WritesthClass();
            a.SetDataOne("Triangle area is:");
            Console.WriteLine("{0}", Tri.MianjiIs());
        }
    }
}

[operation results]
Input three sides of triangle (right triangle is selected): 5, 12, 13, output result: 30

[experience]
With the first program, this programming is relatively easy. There is only one problem:

The framed part was originally written with only one CosB, but the result was always wrong, which made me very confused and curious. I thought the program could not be wrong (this time the program was completed by some changes in the previous method). At a casual glance, I found that the error was actually caused by a problem that was not a problem.

Experiment 2

[Objective] to establish an experimental consumables management system

[experimental requirements]

Design a consumables management class to save and record laboratory consumables classification and records. Members of this class include consumable name, user and laboratory stock. At least two methods are provided:

store consumables warehousing

show display consumables information

When the program is running, you can input the total number of consumables to be warehoused from the console, create a consumables class object array according to the total number, then input data, and finally sort by consumables name, user or laboratory stock.

[experiment code]

using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.InteropServices;

namespace Homework2_3
{
    class Program
    {
        private string namei;
        private int total;
        public Program()        //In this function, the name string and the total number are initialized
        {
            namei = "";
            total = 0;
        }
        public Program(string namei, int total)     //Constructor
        {
            this.namei = namei;
            this.total = total;
        }
        public void Store(ref Program program)      
        {
            namei = program.namei;
            total = program.total;
        }
        public void Show()      //Output function
        {
            Console.WriteLine("Namei:{0}, Total:{1}", namei, total);
        }
        public string Namei     //Name of experimental equipment
        {
            get { return namei; }
            set { namei = value; }
        }
        public int Total
        {
            get{ return total; }
            set{ total = value; }

        }
    }
    class Homework2_3
    {
        static void Main(string[] args)     //Main function of program entry
        {

            Homework2_3 T = new Homework2_3();      //instantiation 
            Program[] qijian;
            int[] index;
           
            int i,k;
            Program program= new Program();
            Console.WriteLine("Please enter the total number of devices to be warehoused:");
            string sline = Console.ReadLine();      //Enter an integer
            int num = int.Parse(sline);
            qijian = new Program[num];
            for (i = 0; i < num; i++)
                 qijian[i] = new Program();
            index = new int[num];
                for (i=0;i<num;i++)
            {
                Console.WriteLine("Please enter device name:");       //Input character
                program.Namei = Console.ReadLine();
                Console.WriteLine("Please enter the total stock in quantity:");      //Enter integer
                sline = Console.ReadLine();
                program.Total = int.Parse(sline);
                qijian[i].Store(ref program);
                index[i] = i;

            }
            Console.Write("If you want to sort, press 1");    //End input
            sline = Console.ReadLine();
            int choice = int.Parse(sline);
            switch(choice)
            {
                case 1:
                    T.SortNamei(qijian, index);
                    break;
            }
            for(i=0;i<num;i++)
            {
                k = index[i];
                (qijian[k]).Show();
            }
            Console.Read();
        }
        void SortNamei(Program[] qijian,int[] index)
        {
            int i, j, m, n, temp;
            for(m=0;m<index.Length-1;m++)       //bubble sort 
                for(n=0;n<index.Length-m-1;n++)
                {
                    i = index[n];
                    j = index[n + 1];
                    if(string.Compare(qijian[i].Namei,qijian[j].Namei)>0)
                    {
                        temp = index[n];
                        index[n] = index[n + 1];index[n + 1] = temp;
                    }
                }
        }
    }
    
 }

[operation results]

[experience]

When writing this program, I just conceived it at the beginning, but I was not sure what to do in many places, so I used the "student management system" program in books for reference. After reading and understanding it, I wrote a similar program based on it. In the process of imitation, I inevitably missed one or two lines, and then there was a serious BUG in the whole program, which also made me more deeply understand the significance of this line of program.

Missing code:

index = new int[num];

Location in the program:

report errors:

Experiment 3
[experimental purpose] write a window program

[generation window]
Click the generated exe file to display a simple "login interface":

Enter user name and password:

Enter the system:

Click "consumables information display":

After exiting, click the second "consumables information modification". The system is temporarily "not open" because the database could not be connected:

[experiment code]

  1. login interface
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 homework2_2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Button1_Click(object sender, EventArgs e)
        {
            if(textBoxyhm.Text ==string.Empty|| textBoxmm.Text==string.Empty)
            {
                MessageBox.Show("Please enter complete information!");
                return;
            }
            if(!textBoxyhm.Text.Equals ("SDU")||!textBoxmm.Text.Equals("sdu"))
            {
                MessageBox.Show("Please enter the correct information!","Tips");
            }
            else
            {
                //Enter the system
                SystemForm systemfrm = new SystemForm();
                systemfrm.ShowDialog();
                this.Close();
             }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            textBoxyhm.Clear();
            textBoxmm.Clear();
        }

        private void Label1_Click(object sender, EventArgs e)
        {

        }

        private void TextBoxyhm_TextChanged(object sender, EventArgs e)
        {

        }

        private void TextBoxmm_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

effect:

2. System interface

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 homework2_2
{
    public partial class SystemForm : Form
    {
        public SystemForm()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void SystemForm_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create an experimental consumables information query form
            SearchForm searchfrm = new SearchForm();
            searchfrm.ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //Create experimental consumables information modification form
            ModifyForm modifyfrm = new ModifyForm();
            modifyfrm.ShowDialog();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Create experimental consumables information entry form
            NoteForm notefrm = new NoteForm();
            notefrm.ShowDialog();
        }
    }
}

3. Experimental consumables information query interface:

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 homework2_2
{
    public partial class SearchForm : Form
    {
        public SearchForm()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void SearchForm_Load(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }
    }
}

4. Experimental consumables information modification / entry interface:

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 homework2_2
{
    public partial class NoteForm : Form
    {
        public NoteForm()
        {
            InitializeComponent();
        }

        private void NoteForm_Load(object sender, EventArgs e)
        {

        }
}

[experimental thoughts]
Looking at the code you typed, you can run a real window and generate a "system". I feel very happy. I think if I have the opportunity, I want to put it into practice and make a real project that can be applied.

Topics: C# Class