Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Example :
Input Two Any Value With Int Type, Call Them 'A', 'B'.
User Can Input A Positive Value For How Many Times The System Creates A Random Number 'M' , A <= M < B.
The System Will Create Random Number 'M' Between 'A' And 'B'.
The Winform Calculates Random Number's Result And Show Them Out.

Hi All, I Create A Bad Coding. Although It Can Work, But The Processing System Struct Was Horrible.
How Do I Do To Improve My Coding Ability. If Anyone Can Help And Give Me Some Suggestions Or Through Direction.
I Need To Fix My Code To More Clean, Readability.How I Start My Coding Let The Winform Become More Completely. Thanks Guys.

GitHub - worldpeaceend/RandomNumber: input two any value with int type, call them a, b.[^]

What I have tried:

The Exam Need To Use List<List<int>>, And Dictionary<int, int> To Finish. I Can Not Totally UnderStand How To Use 'Key' And 'Value' Of List And Dictionary.
At First, I Try To Use Array To Finish The System Function.
But The Winform Become More And More Terrible.
Posted
Updated 15-Nov-21 6:44am
v2
Comments
Richard MacCutchan 7-Nov-21 1:45am    
Why do you need a Dictionary? Create a simple List<int> to hold the random numbers as you generate them. You can then use that list to populate a ListBox on your form to display all the generated values.
Member 14430889 7-Nov-21 17:33pm    
Thanks your kindly suggestion. I was asked to try to use List<list<int>, and Dictionary<int, int=""> to finish in this practice section at first.I just learn the knowledge only List.Add, Dictionary.Add. QQ. I build a Array to complete this Winform function and let it be work. And others told me that the system is better if it include "OOP". I need some help it someone can give me a easy sample code or comment how to start and think step by setp with OOP.
https://drive.google.com/file/d/1U6WOpnkxQQLCMf_zuSnuneyMm39q1xdi/view?usp=sharing
Richard MacCutchan 8-Nov-21 3:57am    
Take a look at .NET Book Zero by Charles Petzold[^]. It has plenty of samples and is an excellent introduction to C#, .NET and OOP.
Member 14430889 9-Nov-21 3:09am    
Great Useful, I Appreciate Your Help Very Much.

Quote:
I Can Not Totally UnderStand How To Use 'Key' And 'Value' Of List And Dictionary.

Lists don't have "Key" or "Value" - dictionaries do because they store two bits of information: a Key which must be unique and a Value which is associated with that key.
For example, a Dictionary<int, Product> might use the ProductID as the Key and the Product itself as the Value: then you use it by supplying the ID Key and acess the Product from that:
C#
string desc = products[prodID].Description;
int stockLevl = products[prodID].InStock;
A List doesn't do that: it just stores the Products and allows you to access them by index:
C#
for (int i = 0; i < products.Count; i++)
   {
   Console.WriteLine($"{products[i].Description}: {products[i].Instock}");
   }


To be honest, if you don't understand the difference between a Dictionary and a List, then that probably explains why your code is low quality - you need to learn the basics and get them down pretty solidly before you start coding complicated apps.

We can't tell you how to improve code we haven't looked at - and I'm certainly not bouncing off to GitHub to look through a whole app to work out what you did so badly - so I'll just say it again: learn the basics well. Until they are instinctive, you can't build good code on top of them.
 
Share this answer
 
v2
Comments
BillWoodruff 7-Nov-21 13:56pm    
+5
Member 14430889 7-Nov-21 17:42pm    
Thanks for your kindly suggestion. Could you give me some easy comments in my codes. How to start use OOP and use List , Dictionary.
it needn't completely function to work, If you have any free time.
https://drive.google.com/file/d/1U6WOpnkxQQLCMf_zuSnuneyMm39q1xdi/view?usp=sharing
OriginalGriff 8-Nov-21 2:29am    
We aren't here to teach you C#: it's far too big a subject for little text boxes like these, there are whole books written on the subject (many of them well over 1,000 pages long!).
In addition to Richard MacCutchan's and OriginalGriff's excellent advice:

Break the problem into small steps:

1) create three controls on the Form for text/number entry

1a) verify that you can get valid integer values from those controls: use 'TryGetValue for 'Textboxes; or, consider using 'NumericUpDown controls.

2) verify your Random function will return a number in the range you specify

3) using the valid integer values, execute a for-loop #m times, and write the random number to the screen, or, save the random numbers in a List you can then present in some way on the Form.
 
Share this answer
 
Comments
Member 14430889 7-Nov-21 17:44pm    
Thanks for your kindly suggestion. Could you give me some easy comments in my codes. How to start use OOP or fix my bad coding.
it needn't completely function to work, If you have any free time.
https://drive.google.com/file/d/1U6WOpnkxQQLCMf_zuSnuneyMm39q1xdi/view?usp=sharing
BillWoodruff 7-Nov-21 17:50pm    
Hi, i am here to teach you how to help yourself develop your own code, not to write code for you.

Your question is relatively simple: start by completing the steps i outlined for you in my answer. Post your code here, and ask specific questions about the code.

cheers, Bill
Member 14430889 7-Nov-21 18:26pm    
My mistasks, sorry about what I saying. I wish you can look at my code if you have been not, but not help me to write. I still can not to judge what is clean code, or not. Might I can using imitate to understand more that I thought before I get the improtant point. There has different way to create more ideas and I will try it all. I love coding but it seems much confus stand by me ever and ever, if i can not switch the basic skills to become useful tools . Thanks you again.
BillWoodruff 7-Nov-21 20:36pm    
no apology necessary, but, my time here is limited; any code you post here i will look at. i think you'll find folks here, or, on StackOverFlow, will not go to any external site to view content (security issues).

whatever your code is, i believe it must provide the three facilities i describe in my answer.

cheers, Bill
Before Fix (Horrible) :

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;
using System.Threading;

namespace WindowsFormsApp_RandNumber_1029
{
	public partial class Form1 : Form
	{
		int numberMax = 0, numberMin = 0, 
			numberSize = 0, numberCount = 0,
			numberStart = 0, numberEnd = 0,
			numberSearch = 0, numberRand = 0,
			numReg = 0 , saveCount = 0,
			totalTimes = 0;

		int[] numberArray, valueArray, countArray;

		Random randSeed = new Random();

		private void btn_Click_Click(object sender, EventArgs e)
		{
			if (checkInputValueType())
			{
				checkValueSequence(numberStart, numberEnd);

				numReg = 0;
				saveCount = 0;
				totalTimes = 0;
				dataView_Result.Rows.Clear();

				numberSize = numberMax - numberMin + 1;

				numReg = numberMin;

				numberArray = new int[numberSize];
				valueArray = new int[numberSize];
				countArray = new int[numberSize];

				for (int i = 0; i < numberSize; ++i)
				{
					numberArray[i] = i+1;
					valueArray[i] = numReg;
					numReg += 1;
					countArray[i] = 0;
				}

				for (int j = 0; j < numberCount; ++j)
				{
					numberRand = randSeed.Next(numberMin, (numberMax+1));
					for (int k = 0; k < valueArray.Count(); ++k)
					{
						if (numberRand.Equals(valueArray[k]))
						{
							saveCount = countArray[k];
							saveCount += 1;
							countArray[k] = saveCount;
						}
					}
				}

				for (int m= 0; m < numberArray.Count(); ++m)
				{
					totalTimes = totalTimes + countArray[m];
					dataView_Result.Rows.Add(numberArray[m], valueArray[m], 
                    countArray[m], totalTimes);					
				}

				if (numberSearch > numberMax || numberSearch < numberMin)
				{
					MessageBox.Show(@"Search Target Not Exist !");
				}
				else
				{
					for (int n = 0; n < valueArray.Count(); ++n)
					{
						if (numberSearch.Equals(valueArray[n]))
						{
							MessageBox.Show(@"Target Is: " + valueArray[n] +
                            " , " + countArray[n] + " Times");
						}
					}
				}
			}
			else
			{
				MessageBox.Show("Error Values !");
			}

		}

		public Form1()
		{
			InitializeComponent();
            Form.CheckForIllegalCrossThreadCalls = false;

			dataResult();
        }

		private bool checkInputValueType()
		{
			bool valueTypeOK = int.TryParse(tBox_Start.Text, out numberStart);
			if (!valueTypeOK)
			{
				MessageBox.Show(@"Only Int Type Value !");
				return false;
			}

			valueTypeOK = int.TryParse(tBox_End.Text, out numberEnd);
			if (!valueTypeOK)
			{
				MessageBox.Show(@"Only Int Type Value !");
				return false;
			}

			valueTypeOK = int.TryParse(tBox_Count.Text, out numberCount);
			if (!valueTypeOK)
			{
				MessageBox.Show(@"Only Int Type Value !");
				return false;
			}
			else
			{
				if (!(numberCount > 0))
				{
					MessageBox.Show(@"Only Positive Values !");
					return false;
				}
			}

			valueTypeOK = int.TryParse(tBox_Search.Text, out numberSearch);
			if (!valueTypeOK)
			{
				MessageBox.Show(@"Only Int Type Value !");
				return false;
			}

			return true;
		}

		private void checkValueSequence(int _first, int _second)
		{
			if (_first > _second)
			{
				numberMax = _first;
				numberMin = _second;
			}
			else if (_first < _second)
			{
				numberMax = _second;
				numberMin = _first;
			}
			else
				numberMax = numberMin = _first;
		}

		private void dataResult()
		{
			DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
			column1.HeaderText = "Sequence";

			DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
			column2.HeaderText = "Random Number";

			DataGridViewTextBoxColumn column3 = new DataGridViewTextBoxColumn();
			column3.HeaderText = "Times";

			DataGridViewTextBoxColumn column4 = new DataGridViewTextBoxColumn();
			column4.HeaderText = "Cumulative Times";

			dataView_Result.Columns.Clear();
			dataView_Result.Columns.Add(column1);
			dataView_Result.Columns.Add(column2);
			dataView_Result.Columns.Add(column3);
			dataView_Result.Columns.Add(column4);
		}
	}
}



After Fix (Not Best, But More Clean) :
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;
using System.Threading;

namespace WindowsFormsApp_RandNumber_1029
{
	public partial class Form1 : Form
	{
		Random randSeed = new Random();

		private void ButtonClickEvent(object sender, EventArgs e)
		{
			int valueStart, valueEnd, 
				valueCount,
				valueMax, valueMin,
				valueSearch,
				sumCount = 0;

			Dictionary<int, int> numberDict = new Dictionary<int, int>();

			if ( int.TryParse(tBox_Start.Text, out valueStart) && 
				 int.TryParse(tBox_End.Text, out valueEnd) &&
				(int.TryParse(tBox_Count.Text, out valueCount) && 
                 valueCount > 0) &&
				 int.TryParse(tBox_Search.Text, out valueSearch))
			{
				valueMax = Math.Max(valueStart, valueEnd);
				valueMin = Math.Min(valueStart, valueEnd);

				for (int i=0; i<valueCount; ++i)
				{
					int randNum = randSeed.Next(valueMin, valueMax + 1);

					if (!numberDict.ContainsKey(randNum))
					{
						numberDict.Add(randNum, 1);
					}
					else
					{
						numberDict[randNum] += 1;
					}
				}

				var numQuery = from num in numberDict
							   orderby num.Key
							   select num;

				dataView_Result.Rows.Clear();

				foreach (KeyValuePair<int, int> kvp in numQuery)
				{
					sumCount += kvp.Value;
					dataView_Result.Rows.Add( kvp.Key,
											  kvp.Value,
											  sumCount);
				}

				if (numberDict.Keys.Contains(valueSearch))
				{
					string howMuchTimes = numberDict[valueSearch] > 1 ?
                    " Times" : " Time";
					MessageBox.Show(@"Find Target: " + valueSearch +
                    " , " + numberDict[valueSearch] + howMuchTimes);
				}
				else
				{
					MessageBox.Show(@"Can Not Find Target !");
				}

			}
			else
			{
				MessageBox.Show(@"Input Value Type Error !");
			}

		}

		public Form1()
		{
			InitializeComponent();

			btn_Click.Click += new EventHandler(ButtonClickEvent);

			InitialResult();
		}

		private void InitialResult()
		{
			DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
			column1.HeaderText = "Random Number";

			DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
			column2.HeaderText = "Result Count";

			DataGridViewTextBoxColumn column3 = new DataGridViewTextBoxColumn();
			column3.HeaderText = "Sum Of Total Count";

			dataView_Result.Columns.Clear();
			dataView_Result.Columns.Add(column1);
			dataView_Result.Columns.Add(column2);
			dataView_Result.Columns.Add(column3);
		}

    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900