Displaying random numbers in C# - 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());
}
}

Related

What error messaging do i add to my windows forms C# program?

My program is a prime numbers C# program and I need error messaging that shows what happens when I add letters and/or larger numbers first in the textboxes.
Here is my code:
namespace Task_2_Prime_Numbers
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btcalculate_Click(object sender, EventArgs e)
{
// Find all Prime numbers between the first and last prime numbers
int firstnum = Convert.ToInt32(number1.Text);
int lastnum = Convert.ToInt32(number2.Text);
IbPrime.Items.Clear();
// See which numbers are factors and add them to the list box
for (int i = firstnum; i <= lastnum; i++)
{
if (IsPrime(i))
{
IbPrime.Items.Add(i);
}
}
}
private bool IsPrime(int num)
{
if (num < 2)
return false;
// Looks for a number that evenly divides the sum
for (int i = 2; i <= num / 2; i++)
if (num % i == 0)
return false;
return true;
}
}
}
Use int.TryParse.
int firstnum, lastnum;
if (!int.TryParse(number1.Text, out firstnum)){
// Error
}
if (!int.TryParse(number2.Text, out lastnum)){
// Error
}
if (firstnum >= lastnum){
// Error
}

Array doesn't display in the message box - 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";
}

labels are not updating on Windows Form

In a math game that I programming, my Windows Form has labels in it where the numbers appear for the sum.
When I click button1, they should change to other numbers, but they don't. The labels that should change are called lblNumber1 and lblNumber2.
Here is my code:
public partial class plussommen : Form
{
int counter = 0;
int correct = 0;
int incorrect = 0;
Random rand = new Random();
int number1, number2;
int answer;
string sum;
public plussommen()
{
InitializeComponent();
number1 = rand.Next(1, 50);
number2 = rand.Next(1, 50);
sum = number1 + " + " + number2 + " = ";
answer = number1 + number2;
}
private void plussommen_Load(object sender, EventArgs e)
{
if (counter < 5)
{
lblNumber1.Text = number1.ToString();
lblNumber2.Text = number2.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
lblCorrect.Text = correct.ToString();
lblIncorrect.Text = incorrect.ToString();
if (textBox1.Text == answer.ToString())
{
MessageBox.Show("Answer correct!");
correct = correct + 1;
}
else
{
MessageBox.Show("Answer incorrect!");
incorrect = incorrect + 1;
}
if (counter < 5)
{
lblNumber1.Text = number1.ToString();
lblNumber2.Text = number2.ToString();
}
else
{
if (counter == 5)
{
MessageBox.Show("You've made five sums, choose another kind of sum.");
this.Close();
Form1 menu = new Form1();
menu.Show();
}
}
}
}
To change the value on the labels on every click, you need to generate new random numbers each time.
if (counter < 5)
{
number1 = rand.Next(1, 50);
number2 = rand.Next(1, 50);
lblNumber1.Text = number1.ToString();
lblNumber2.Text = number2.ToString();
}
In your code, you are not changing the values of number1 and number2 at any time after initialization. This is why they are not updating after every button click.
What you need to do is update the numbers and the answer after every click:
private void button1_Click(object sender, EventArgs e)
{
//...
if (counter < 5)
{
number1 = rand.Next(1, 50);
number2 = rand.Next(1, 50);
answer = number1 + number2;
lblNumber1.Text = number1.ToString();
lblNumber2.Text = number2.ToString();
}
//...
}

VS WPF Program keeps crashing when checking if statement

i just finished making an WPF program by Visual Studio 2012 about a simple Students Grading System.
all goes fine and it shows no error or invalid statements (red lines)
and there is a submit button, but whenever i press it a second time, the program crashes.
i checked my code several times and i can't find a solution. so it might be bother :S
the program works such as this:
the user have to enter a number of students to put grades. --> press OK, list of fields appear, when the user done inputting grades --> press submit. the values are all entered to 2 arrays, one for names and the other for grades which will be converted to letters.
the fields will be cleared for the second students, and so on until the number of students reached. the program should give a messagebox with containing the names and their Letter-grades.
using System.IO;
namespace Grading_System_Project_3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static int nbofstudents;
public double m1, m2, p1, p2, f;
public int i = 0;
public int l;
public double avg;
public string name;
public char fg;
public char[] gr;
public string[] names;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Convert.ToInt32(textBox1.Text) <= 0)
{
MessageBox.Show("Please Enter a valid students number");
}
else
{
nbofstudents = Convert.ToInt32(textBox1.Text);
StreamWriter SW = File.CreateText(#"C:\grades.txt");
SW.Close();
textBox2.Visibility = System.Windows.Visibility.Visible;
textBox3.Visibility = System.Windows.Visibility.Visible;
textBox4.Visibility = System.Windows.Visibility.Visible;
textBox5.Visibility = System.Windows.Visibility.Visible;
textBox6.Visibility = System.Windows.Visibility.Visible;
textBox7.Visibility = System.Windows.Visibility.Visible;
label2.Visibility = System.Windows.Visibility.Visible;
label3.Visibility = System.Windows.Visibility.Visible;
label4.Visibility = System.Windows.Visibility.Visible;
label5.Visibility = System.Windows.Visibility.Visible;
label6.Visibility = System.Windows.Visibility.Visible;
label7.Visibility = System.Windows.Visibility.Visible;
}
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
StreamWriter sw2 = new StreamWriter(#"C:\grades.txt");
if (i < nbofstudents)
{
name = textBox2.Text;
m1 = Convert.ToInt32(textBox3.Text);
m2 = Convert.ToInt32(textBox4.Text);
p1 = Convert.ToInt32(textBox5.Text);
p2 = Convert.ToInt32(textBox6.Text);
f = Convert.ToInt32(textBox7.Text);
avg = (m1 + m2 + p1 + p2 + f) / 5;
if (avg >= 0 && avg <= 59)
{
fg = 'F';
}
else if (avg >= 60 && avg <= 69)
{
fg = 'D';
}
else if (avg >= 70 && avg <= 79)
{
fg = 'C';
}
else if (avg >= 80 && avg <= 89)
{
fg = 'B';
}
else if (avg >= 90 && avg <= 100)
{
fg = 'A';
}
string temp = Convert.ToString(fg);
try
{
sw2.WriteLine(name + "\t" + temp);
sw2.WriteLine();
sw2.Close();
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
i++;
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
}
else
{
try
{
StreamReader rf = new StreamReader(#"C:\grades.txt");
string s = "";
while ((s = rf.ReadLine()) != null)
{
MessageBox.Show(rf.ReadLine());
}
rf.Close();
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}

select name from array, selected name print in listBox1 and remaining in listBox2

I am having this error:
Index was out of range. Must be non-negative and less than the size of the collection.
I spent a long time trying to solve it, but I could not. Please I need help
public partial class Form1 : Form
{
string[] generate = new string[] {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Name14","Name15","Name16","Name17","Name18","Name19","Name20" };
string[] n = new string[] { "Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10", "Name11", "Name12", "Name13", "Name14", "Name15", "Name16", "Name17", "Name18", "Name19", "Name20" };
String[] a = new String[20];
string name;
int Num;
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) // START btn
{
Num = int.Parse(textBox1.Text);
if (Num < 20)
{
if (generate.Length >= Num)
{
for (int i = Num; i > 0; i--)
{
name = generate.ElementAt(i);
listBox1.Items.Add(name); // Print it to list1
generate = generate.Where(s => s != name).ToArray(); // Delete name after using
}
}
else MessageBox.Show("Sorry, remaining names =" + generate.Length);
listBox2.Items.Clear();
listBox2.Items.AddRange(generate);
}
else MessageBox.Show("Max name is 20!");
}
Problem is that indexes in 20 elements array go from 0 to 19. In your code, you allow 20, wich makes an error
if (generate.Length >= Num)
You should remove = sign. Also, you should add = sign to for loop
for (int i = Num; i > 0; i--)
so you can include the first element of array (the one with index of 0).
Basically, if condition should look like this:
if (generate.Length > Num)
and for loop like this:
for (int i = Num; i >= 0; i--)
Try 19 instead of 20 because when you count elements in an array you start by zero.
this will let you place 20 in your textbox
Num = int.Parse(textBox1.Text);
if (Num <= 20)
{
if (generate.Length >= Num)
{
for (int i = Num - 1; i >= 0; i--)
{
name = generate.ElementAt(i);
listBox1.Items.Add(name); // Print it to list1
generate = generate.Where(s => s != name).ToArray(); // Delete name after using
}
}
else MessageBox.Show("Sorry, remaining names =" + generate.Length);
listBox2.Items.Clear();
listBox2.Items.AddRange(generate);
}
else MessageBox.Show("Max name is 20!");

Categories