Array doesn't display in the message box - C# - c#

I'm trying to display 5 scores in an array, but unfortunately all I get in the message box for the results is 0.
Any help would be appreciated.
public partial class Form1 : Form
{
private int[] scoresArray = new int[5];
private int scoreTotal = 0;
private int scoreCount = 0;
public Form1()
{
InitializeComponent();
}
when the add button is clicked the scores are stored in the array up to 5 times.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (txtScore.Text == "")
{
MessageBox.Show("Score is required", "Entry Error");
}
else
{
int score = Convert.ToInt32(txtScore.Text);
decimal average = 0;
if (score >= 0 && score <= 100)
{
if (scoreCount != 4)
{
scoreTotal += score;
scoresArray[scoreCount] = score;
scoreCount++;
average = scoreTotal / scoreCount;
}
else
{
MessageBox.Show("Array is full");
}
txtScoreTotal.Text = scoreTotal.ToString();
txtScoreCount.Text = (scoreCount + 1).ToString();
txtAverage.Text = average.ToString();
}
else
{
MessageBox.Show("Score must be greater than 0 and less than or equal to 100.", "Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid number for the Score field.", "Entry Error");
}
txtScore.Focus();
}
private void btnDisplayScores_Click(object sender, EventArgs e)
{
string message = "";
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
MessageBox.Show(message, "Scores");
}

You keep overwriting message in this loop:
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
So it's only ever going to show the last value. You probably want to append to it instead:
for (int i = 0; i < scoresArray.Length; i++)
{
message += scoresArray[i].ToString() + "\n";
}

Related

how can i adding up numbers from an array using the foreach loop

i've made an array with numbers.
i want to ad up the numbers form the array and show the result in a textbox.
i've to use the foreach loop.
i've already searched on the internet but i can't find anything that helped me.
this is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnsortar_Click(object sender, EventArgs e)
{
//opdr 9
int[] getallen = { 4,5,9,8,31,44,76,63,88,59 };
int index = 1;
int lengteArray = getallen.Length;
tbsortar.Text = getallen[0].ToString();
while (index < lengteArray)
{
Array.Sort(getallen);
tbsortar.Text = tbsortar.Text + "," + getallen[index].ToString();
index++;
}
//opdr 10
string[] namen = { "kees", "jan", "piet", "henk" };
Array.Sort(namen);
int lengteArray1 = namen.Length;
tbopdr10.Text = namen[0];
for (int i=1; i<lengteArray1; i++)
{
string newLine = Environment.NewLine;
tbopdr10.Text = tbopdr10.Text +newLine + namen[i] ;
}
//opdr 11
double totaal = 0;
foreach(int getal in getallen)
{
//toaal van getallen is 392
totaal += getal;
tbopdr11.Text = tbopdr11.Text + totaal;
}
}
}
Try this:
int[] Numbers = { 1, 2, 3 };
int Result = 0;
for (int i = 0; i < Numbers.Length; i++)
{
Result += Numbers[i];
}
TextBox1.Text = System.Convert.ToString(Result);
The textbox's name is TextBox1.
can't you just use sum?
getallen.Sum()
https://dotnetfiddle.net/sTn1kp

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

Printing an array in a GUI label in visual studio with C#

So I am trying to figure out how to print out a list of bowling names and scores in my program. It is way simple when using a console. I am trying to figure out how to print the array into a label on a GUI? Any suggestions? I tried if/else if statements but obviously it didn't work.
Here is my form code:
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 Project_9
{
public partial class Form1 : Form
{
//Declare a reference variable to the class
private BowlingTeam myBowlingTeam;
const int MAX = 20;
const int TWO = 2;
int size = 0;
int count = 0;
//Array to store the names and scores so they can be printed
string[] nameAndScoreArray = new string[MAX];
public Form1()
{
InitializeComponent();
myBowlingTeam = new BowlingTeam();//Create a BowlingTeam object with the default constructor
}
//ExitToolStripMenuItem1_Click
//Purpose: To close the application when clicked
//Parameters: The sending object and the event arguments
//Returns: nothing
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//Enter Button Clicked
//Purpose: To store the info in an array when the button is pressed
//Parameters: The sending object and the event arguments
//Returns: nothing
private void button1_Click(object sender, EventArgs e)
{
//Get info from the text box and store it in a variable
string aNameAndScore = nameTextBox.Text;
//Set the name and score
myBowlingTeam.SetNameAndScore(aNameAndScore);
//Get the information from the text box and store it in a variable
string nameAndScore = myBowlingTeam.GetNameAndScore();
if (nameAndScore != "")
{
string printName = "";
string printScore = "";
//Split the string into two separte pieces of data
myBowlingTeam.SplitAndDisperseArray();
//Print the name of the bowler in the score box
string name = myBowlingTeam.GetAName();
//Change the int into a string then
//print the score of the bowler in the score box
int score = myBowlingTeam.GetAScore();
string strScore = String.Format("{0:d}", score);
//Store the name and score in an array to use them to print out the
//names and scores later
if (size < MAX)
{
nameAndScoreArray[size] = name;
nameAndScoreArray[size + 1] = strScore;
printName = nameAndScoreArray[size];
printScore = nameAndScoreArray[size + 1];
}
string strNameAndScore = printName + " " + printScore;
if (scoreLabel.Text == "")
{
scoreLabel.Text = strNameAndScore;
}
else if(scoreLabelTwo.Text == "")
{
scoreLabelTwo.Text = strNameAndScore;
}
else if(scoreLabelThree.Text == "")
{
scoreLabelThree.Text = strNameAndScore;
}
else if(scoreLabelFour.Text == "")
{
scoreLabelFour.Text = strNameAndScore;
}
else if(scoreLabelFive.Text == "")
{
scoreLabelFive.Text = strNameAndScore;
}
else if(scoreLabelSix.Text == "")
{
scoreLabelSix.Text = strNameAndScore;
}
else if(scoreLabelSeven.Text == "")
{
scoreLabelSeven.Text = strNameAndScore;
}
else if(scoreLabelEight.Text == "")
{
scoreLabelEight.Text = strNameAndScore;
}
else if(scoreLabelNine.Text == "")
{
scoreLabelNine.Text = strNameAndScore;
}
else if(scoreLabelTen.Text == "")
{
scoreLabelTen.Text = strNameAndScore;
}
//Clear the text box
nameTextBox.Clear();
}
else//If there is nothing in the text box
{
//Calculate the highest score and get the bowler's name
int highestScore = myBowlingTeam.CalcHighestScore();
string highestName = myBowlingTeam.GetHighestBowlerName();
//Calaculate the lowest score and get the bowler's name
int lowestScore = myBowlingTeam.CalcLowestScore();
string lowestName = myBowlingTeam.GetLowestBowlerName();
//Calculate the avg acore
double avgScore = myBowlingTeam.CalcAvgScore();
//Convert the numbers into strings
string strHighScore = String.Format("{0:d}", highestScore);
string strLowScore = String.Format("{0:d}", lowestScore);
string strAvgScore = String.Format("{0:f2}", avgScore);
//Display the information in the appropriate labels
highScoreNameLabel.Text = highestName;
highScoreLabel.Text = strHighScore;
lowScoreNameLabel.Text = lowestName;
lowScoreLabel.Text = strLowScore;
avgScoreLabel.Text = strAvgScore;
}
}
//Print Scores Method
//Purpose: To print the names and scores
//Parameters: An Array
//Returns: Nothing
public void PrintNamesAndScores(ref string[] anArray)
{
for(int i = 0; i < size; i++)
{
Console.WriteLine("{0} {1:d}", anArray[i], anArray[i + 1]);
i++;
}
}
//Nothing
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
}
// nothing
private void nameTextBox_KeyDown(object sender, KeyEventArgs e)
{
}
//Nothing
private void scoreTextBox_KeyDown(object sender, KeyEventArgs e)
{
}
//Nothing
private void label10_Click(object sender, EventArgs e)
{
}
//nothing
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Here is my class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_9
{
class BowlingTeam
{
const int MAX = 10;
//local variables
int sizeOfName = 0;
int sizeOfScore = 0;
//Declare Private Data Members
private string nameAndScore = "";
private string name = "";
private int score = 0;
private string[] nameArray = new string[MAX];
private int[] scoreArray = new int[MAX];
private string[] nameAndScoreArray = new string[MAX];
//Default Constructor
//Purpose: To set the initial values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam()
{
nameAndScore = "";
name = "";
score = 0;
for(int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for(int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Parameterized Constructor
//Purpose: To set the values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam(string aString)
{
nameAndScore = aString;
name = "";
score = 0;
for (int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for (int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Split the Input Method
//Purpose: To Split up the data in the array
//Parameters: An array of strings
//Returns: Nothing
public void SplitAndDisperseArray()
{
nameAndScoreArray = nameAndScore.Split();
name = nameAndScoreArray[0];
score = int.Parse(nameAndScoreArray[1]);
//Place the name and the score in their one arrays
PlaceInNameArray(name);
PlaceInScoreArray(score);
}
//Find Highest Score Method
//Purpose: To find the highest score
//Parameters: An array of int
//Returns: An int
public int CalcHighestScore()
{
int highestScore = scoreArray[0];
for (int i = 1; i < sizeOfScore; i++ )
{
if (highestScore > scoreArray[i])
{
highestScore = highestScore;
}
else
{
highestScore = scoreArray[i];
}
}
return highestScore;
}
//Find Lowest Score Method
//Purpose: To find the lowest score
//Parameters: An array of int
//Returns: An int
public int CalcLowestScore()
{
int lowestScore = scoreArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (lowestScore < scoreArray[i])
{
lowestScore = lowestScore;
}
else
{
lowestScore = scoreArray[i];
}
}
return lowestScore;
}
//Calulate Avg. Score Method
//Purpose: To calculate the avg score
//Parameters: An array of int
//Returns: An double
public double CalcAvgScore()
{
int sum = 0;
double avg = sizeOfScore;
//Add up all of the elements in the array
for (int i = 0; i < sizeOfScore; i++)
{
sum += scoreArray[i];
}
//Divide the sum by the size of the array
return avg = sum / avg;
}
//Set Score Array Method
//Purpose: To put scores in the score array
//Parameters: An int
//Returns: Nothing
public void PlaceInScoreArray(int aScore)
{
scoreArray[sizeOfScore] = score;
sizeOfScore++;
}
//Set Name Array Method
//Purpose: To put names in the names array
//Parameters: A string
//Returns: Nothing
public void PlaceInNameArray(string aName)
{
nameArray[sizeOfName] = name;
sizeOfName++;
}
//Get Name and Score Method
//Purpose: To get the name and score
//Parameters: None
//Returns: A string
public string GetNameAndScore()
{
return nameAndScore;
}
//Set Name and Score Method
//Purpose: To set the name and score
//Parameters: A String
//Returns: None
public void SetNameAndScore(string aNameAndScore)
{
nameAndScore = aNameAndScore;
}
//Get Bowler Name Of Highest Score Method
//Purpose: To get the name of the bowler with the highest score
//Parameters: None
//Returns: A String
public string GetHighestBowlerName()
{
int highestScore = scoreArray[0];
string bowlersName = nameArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (highestScore > scoreArray[i])
{
highestScore = highestScore;
bowlersName = bowlersName;
}
else
{
highestScore = scoreArray[i];
bowlersName = nameArray[i];
}
}
return bowlersName;
}
//Get Bowler Name Of Lowest Score Method
//Purpose: To get the name of the bowler with the lowest score
//Parameters: None
//Returns: A String
public string GetLowestBowlerName()
{
int lowestScore = scoreArray[0];
string bowlersName = nameArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (lowestScore < scoreArray[i])
{
lowestScore = lowestScore;
bowlersName = bowlersName;
}
else
{
lowestScore = scoreArray[i];
bowlersName = nameArray[i];
}
}
return bowlersName;
}
//Print Bowler's Names
//Purpose: To print the names the bowlers
//Parameters: None
//Returns: A String
public string GetAName()
{
string name = "";
for (int i = 0; i < sizeOfName; i++)
{
name = nameArray[i];
}
return name;
}
//Print Bowler's Scores
//Purpose: To print the names the bowlers
//Parameters: None
//Returns: A String
public int GetAScore()
{
int score = 0;
for (int i = 0; i < sizeOfScore; i++)
{
score = scoreArray[i];
}
return score;
}
}
}
As a general solution, I'd suggest that using LINQ to output a list of one String per item and then using String.Join to join them into a single String is the most succinct option, e.g.
myLabel.Text = string.Join(Environment.NewLine, myArray.Select(obj => string.Format("{0}, {1}", obj.Property1, obj.Property2)));

summing selected values of datagridview

I using this code for sum selected cells. Its work good but when user selecte cell where is letter is throws exceptions : ) how can i secure when in selectet cells is letters dont make sum
i asked same question but there i cannot add my code
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
if (!dataGridView1.SelectedCells.Contains(dataGridView1.Rows[i].Cells["cLoadName"]))
{
float nextNumber = 0;
float sumNumbers = 0;
nextNumber = float.Parse(dataGridView1.SelectedCells[i].FormattedValue.ToString());
sumNumbers += nextNumber;
tsslSumSelected.Text = "ჯამი: " + sumNumbers;
tsslTotalSelected.Text = "მონიშნული: " + dataGridView1.SelectedCells.Count.ToString();
}
else
{
}
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
if (!dataGridView1.SelectedCells.Contains(dataGridView1.Rows[i].Cells["cLoadName"]))
{
float nextNumber = 0;
float sumNumbers = 0;
if (float.TryParse(dataGridView1.SelectedCells[i].FormattedValue.ToString(), out nextNumber))
sumNumbers += nextNumber;
tsslSumSelected.Text = "ჯამი: " + sumNumbers;
tsslTotalSelected.Text = "მონიშნული: " + dataGridView1.SelectedCells.Count.ToString();
}
else
{
}
}
}
public void ComputeGridTot()
{
try
{
decimal qty= 0;
decimal price = 0;
decimal tax = 0;
decimal Total = 0;
for (int i = 0; i < drGrdView1.Rows.Count; i++)
{
if (drGrdView1.Rows[i].Cells[7].Value.ToString() == blcnt.ToString())
{
qty += Convert.ToDecimal(drGrdView1.Rows[i].Cells[3].Value);
price += Convert.ToDecimal(drGrdView1.Rows[i].Cells[4].Value);
tax += Convert.ToDecimal(drGrdView1.Rows[i].Cells[5].Value);
Total += Convert.ToDecimal(drGrdView1.Rows[i].Cells[6].Value);
}
}
lblGTax.Text = tax.ToString();
lblGQty.Text = qty.ToString();
lblGPrice.Text = price.ToString();
lblGTot.Text = Total.ToString();
}
catch
{
}
}

Displaying random numbers in C#

I'm trying to design a code where one guess a number. I defined the range which number to display in my listbox. I started to write Random(1,10) but if I enter 11, it still writes in my listbox. How can I just write the number selected from my range, which is 1-10?
Here is a part of my code:
private void btnOk_Click(object sender, EventArgs e)
{
string yourNumber;
yourNumber = textBox1.Text.Trim();
int returnNumber = RandomNumber(1, 10);
int.TryParse(textBox1.Text, out returnNumber);
listBox1.Items.Add(returnNumber);
}
Additional question
If I would like to display a range of number like for example 1-10, how could I do the following? The user will type 11 the program will not accept that.
I made something like this:
int returnNumber = RandomNumber(1, 10);
string yourNumber;
yourNumber = textBox1.Text.Trim();
if(Int32.TryParse(textBox1.Text>=1)) && (Int32.TryParse(textBox1.Text<=10));
{
listBox1.Items.Add(yourNumber);
textBox1.Text = string.Empty;
}
Something is wrong in the program.
Update
For Nathaniel, I tried this one:
int returnNumber=RandomNumber(1,10);
int counter=1;
int yourNumber;
Int32.TryParse(textBox1.Text.Trim(), out yourNumber);
if (yourNumber >=1 && yourNumber <= 10)
{
listBox1.Items.Add(yourNumber);
}
else
{
MessageBox.Show("Please enter a number between 1-10");
}
What I would like to do is design a program for guessing a number. So this is the first part.
Update
Here is my final code, can it be improved? I think the next thing I'll do is to limit the times the user types the input. That means, they can only guess the right number 3 times or 5 times. Not sure where to implement it
namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void btnOk_Click(object sender, EventArgs e)
{
int yourNumber = 0;
Int32.TryParse(textBox1.Text.Trim(), out yourNumber);
if (yourNumber>= rangeNumberMin && yourNumber<=rangeNumberMax)
{
listBox1.Items.Add(yourNumber);
if (yourNumber > randomNumber)
{
listBox2.Items.Add("No the Magic Number is lower than your number");
}
if (yourNumber < randomNumber)
{
listBox2.Items.Add("No, the Magic Number is higher than your number");
}
if(yourNumber==randomNumber)
{
listBox2.Items.Add("You guessed the Magic Number!");
btnRestart.Enabled = true;
}
}
else
{
MessageBox.Show("Please enter a number between " + rangeNumberMin + " to " + rangeNumberMax);
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
listBox1.Items.Clear();
textBox1.Text = null;
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
btnRestart.Enabled = false;
}
}
The line:
int returnNunmber = RandomNumber(1, 10);
does nothing, because in the next line returnNumber is used as an output variable and will be whatever number is in textBox1. Remove the
int.TryParse(textBox1.Text, out returnNumber);
line and it will add a random number from 1 to 10 to your listbox.
EDIT::::
To answer you additional question, try:
private void btnOk_Click(object sender, EventArgs e)
{
string yourNumber;
yourNumber = textBox1.Text.Trim();
int returnNumber;
int.TryParse(textBox1.Text, out returnNumber);
if( returnNumber < 1 || returnNumber > 10) {
returnNumber = RandomNumber(1, 10);
}
listBox1.Items.Add(returnNumber);
}
Some minor changes to your code, condensing a couple lines and adding the limit code, utilizing the list of guesses as the counter:
namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
private const int maxGuesses = 5;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void btnOk_Click(object sender, EventArgs e)
{
int yourNumber = 0;
if (Int32.TryParse(textBox1.Text.Trim(), out yourNumber) &&
yourNumber>= rangeNumberMin && yourNumber<=rangeNumberMax)
{
listBox1.Items.Add(yourNumber);
if (yourNumber > randomNumber)
{
listBox2.Items.Add("No the Magic Number is lower than your number");
}
else if (yourNumber < randomNumber)
{
listBox2.Items.Add("No, the Magic Number is higher than your number");
}
else
{
listBox2.Items.Add("You guessed the Magic Number!");
textBox1.Enabled = false;
btnOk.Enable = false;
btnRestart.Enabled = true;
}
//Will stop on the 5th guess, but guards the case that there were more than 5 guesses
if(listBox1.Items.Count >= maxGuesses && yourNumber != randomNumber)
{
listBox2.Items.Add("You are out of guesses!");
textBox1.Enabled = false;
btnOk.Enable = false;
btnRestart.Enabled = true;
}
}
else
{
MessageBox.Show("Please enter a number between " + rangeNumberMin + " to " + rangeNumberMax);
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
listBox1.Items.Clear();
textBox1.Text = null;
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
btnRestart.Enabled = false;
textBox1.Enabled = true;
btnOk.Enable = true;
}
}
}
Editted to prevent the "You're out of guesses" message when the number is correctly guessed on the last guess.
Lets take that piece by piece:
int returnNumber = RandomNumber(1, 10);
There is no inbuilt RandomNumber function; note that with the Random class, the end value is exclusive, so for a number in a range, you'll need something like:
static readonly Random rand = new Random();
static int Random(int min, int max) {
if(max < min) throw new ArgumentOutOfRangeException("max");
lock(rand) {
return rand.Next(min, max + 1);
}
}
However, you then throw away this value completely:
int.TryParse(textBox1.Text, out returnNumber);
The use of out means that the previous value of returnNumber is ignored completely. I'm not sure what your intent is, but it seems like you just want to check the value:
if(int.TryParse(textBox1.Text, out returnNumber)
&& returnNumber >= 1 && returnNumber <= 10)
{
listBox1.Items.Add(returnNumber);
}
I've tried to look at the last example, but it really isn't clear what you are trying to do - can you clarify?
(edited after question edit and comments)
You would need a counter, which you increment for failed tries - something like:
using System;
using System.Drawing;
using System.Windows.Forms;
class MyForm : Form {
Button btn;
ListBox lst;
TextBox tb;
const int MaxTries = 3, MaxNumber = 10;
int targetNumber, guessCount = 0;
public MyForm() {
targetNumber = new Random().Next(1, MaxNumber + 1);
Text = "Guess a number";
Icon = SystemIcons.Question;
Controls.Add(lst = new ListBox {Dock=DockStyle.Fill});
Controls.Add(btn = new Button {Text="Guess",Dock=DockStyle.Top});
Controls.Add(tb = new TextBox {Dock=DockStyle.Top});
btn.Click += btn_Click;
}
void btn_Click(object sender, EventArgs e) {
int userNumber;
if (int.TryParse(tb.Text.Trim(), out userNumber)) {
if (userNumber < 1 || userNumber > MaxNumber) {
lst.Items.Add("Did I mention... between 1 and " + MaxNumber);
} else {
if (userNumber == targetNumber) {
lst.Items.Add("Well done! You guessed well");
btn.Enabled = false; // all done
} else {
lst.Items.Add(targetNumber < userNumber
? "Try a bit lower" : #"It is bigger than that");
if (++guessCount >= MaxTries) {
btn.Enabled = false;
lst.Items.Add("Oops, should have picked more wisely");
}
}
}
} else {
lst.Items.Add("Nice; now give me a number");
}
}
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}

Categories