views:

749

answers:

3

Hello

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?

I'm quite lost here. Any ideas?

Thanks 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 that: So for example, if 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

==============

hello again thanks Nathaniel for the reply. But 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.

====

Hi again, here is my final code: I would be happy if you could give feedback on how I can do it better. Thanks. 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;
    }
}
+10  A: 

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);            
  }
Nathaniel Flath
hi Nathaniel, thanks for the input. I think it works now;-)
tintincute
oops sorry Nathaniel, i thought it's what I need now. But when I tried it again, if I enter number 1, it displays the random number. And I don't want that. What I would like to do, is display the given number by the user, but it should not exceed to 10
tintincute
+2  A: 

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());
    }
}
Marc Gravell
hi Marc, i posted my final code above. And so far it works. I would be glad if you can give me some input on how to do it better.Thanks
tintincute
hi Marc, i'm not sure where I can implement the "number of tries" here. Do you have any idea? I only want to have it for example to 3 tries and the program will say like, it's finished or it's over.
tintincute
You would need a counter - see update
Marc Gravell
Thanks Marc for this suggestion. I haven't learned yet this [STAThread] and the rest of the line, but I'll give this a try. I would be glad if you have some links about the Application.EnableVisualStyle() etc, not really sure what's their function in the code.Thanks again
tintincute
That is just the boiler-plate when you create a new windows forms project. MSDN lists all of them in detail; STAThread ensures that the UI thread is in a single-threaded apartment (necessary for the Win32/COM controls); EnableVisualStyles() enables XP themes - i.e. it makes it prettier ;-p
Marc Gravell
thanks for the input Marc ;-) MSDN sometimes hard to understand. Anyway, soon I'll learn this topic.
tintincute
+2  A: 

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.

phsr
Hi phsr, thanks for your reply. I have a question for you, the "guessesTaken = 0;" which you initialize where never used. I'm getting an error if I include this in my code
tintincute
Remove the guessesTaken = 0 code. It was dead code from the original way i was planning on implementing the guess limit
phsr
thanks phsr, that's what I did. I already removed it.I also noticed that even though I guess the right number before the limit ends, I still get the message, "You're out of guesses"
tintincute
I've updated my answer that will prevent the "Out of guesses" message from appearing when you guess correctly. I hadnt tested any of this code ;)
phsr