How can I make a code with a string work with or?

10

Apparently I'm having problems with strings :

public partial class Form1 : Form
{
    private int _adicionar;
    private int _retirar;

    public Form1()
    {
        InitializeComponent();
    }

    private void _Random_Click(object sender, EventArgs e)
    {
        Random num = new Random();
        _ValSorteado.Text = num.Next(Convert.ToInt32(_TextValMin.Text), Convert.ToInt32(_TextValMax.Text)).ToString();

        if (_Igual.Checked)
        {
            if (_TextValPalite.Text == _ValSorteado.Text)
            {
                _adicionar = _adicionar + 1;
                _Acerto.Text = Convert.ToString(_adicionar);
            }
            else
            {
                _retirar = _retirar + 1;
                _Errou.Text = Convert.ToString(_retirar);
            }


            if (_Maior.Checked)
            {
                if (_TextValPalite.Text > _ValSorteado.Text)
                {
                    _adicionar = _adicionar + 1;
                    _Acerto.Text = Convert.ToString(_adicionar);
                }
                else
                {
                    _retirar = _retirar + 1;
                    _Errou.Text = Convert.ToString(_retirar);
                }
            }

            if (_Menor.Checked)
            {
                if (_TextValPalite.Text < _ValSorteado.Text)
                {
                    _adicionar = _adicionar + 1;
                    _Acerto.Text = Convert.ToString(_adicionar);
                }
                else
                {
                    _retirar = _retirar + 1;
                    _Errou.Text = Convert.ToString(_retirar);
             }
            }
          }
        }

For equal values (==) and different (! =) I get, but for larger values (>) or smaller (

asked by anonymous 19.05.2016 / 15:38

4 answers

6
  

Note: My answer takes into account that the data entered by the user will be validated separately (perhaps in the% method of% of the component, or something similar) and that in no case will it be possible conversion methods receive invalid values. If you are not sure of the integrity of the values, you should prefer to use Leave as in the @bigown response.

You can not even do this kind of comparison with strings.

You need to convert the types to number.

If your application will use values typed more than once, the solution is to use two TryParse variables. Ex.:

int valorPalpite = Convert.ToInt32(_TextValPalite.Text);
int valorSorteado = Convert.ToInt32(_ValSorteado.Text);

use:

if(valorPalpite < valorSorteado) { ... }

I would save the variables right at the beginning of the click event and then use them to make any validations and / or calculations as needed.

If you prefer, you can do the conversion at the time of verification

if (Convert.ToInt32(_TextValPalite.Text) < Convert.ToInt32(_ValSorteado.Text)) { ... }

Additional :

  • int is not the only way to convert a string to a number, for more details you can see the answers in What is the main difference between int.Parse () and Convert.ToInt32 ()?
  • Variable names are not following the C # naming pattern . The only ones that are following the pattern are Convert.ToInt32 and _adicionar , the rest should not have underscore ( _retirar ).
  • 19.05.2016 / 15:45
    6

    The real problem in this whole code is that it is not dealing well with the text data. Something similar to what happens in the response placed in another question .

    If you want to insist on using the correct text, use the Compare() ". But I do not advise.

    To convert the data to number, since the data entry can not be guaranteed valid, it is only necessary to try the conversion and take some action if the conversion does not work. So all of these form fields need to use a TryParse() to generate a variable with the numeric value. There you can compare as you want.

    private void _Random_Click(object sender, EventArgs e) {
        var num = new Random();
        int valMin;
        if (int.TrypParse(_TextValMin.Text, out valMin)) {
            MessageBox.Show("valor inválido"); //obviamente isto é uma simplificação
            return;
        }
        int valMax;
        if (int.TrypParse(_TextValMax.Text, out valMax)) {
            MessageBox.Show("valor inválido"); //obviamente isto é uma simplificação
            return;
        }
        var valSorteado = num.Next(valMin, valMax);
        _ValSorteado.Text = valSorteado.ToString();
        int valPalpite;
        if (int.TrypParse(_TextValPalpite.Text, out valPalpite)) {
            MessageBox.Show("valor inválido"); //obviamente isto é uma simplificação
            return;
        }
        if (_Igual.Checked) {
            if (valPapite == valSorteado) {
                _Acerto.Text = (++_adicionar).ToString();
            } else {
                _Errou.Text = (++_retirar).ToString();
            }
            if (_Maior.Checked) {
                if (valPalite > valSorteado) {
                    _Acerto.Text = (++_adicionar).ToString();
                } else {
                    _Errou.Text = (++_retirar).ToString();
                }
            }
            if (_Menor.Checked) {
                if (valPalite < valSorteado) {
                    _Acerto.Text = (++_adicionar).ToString();
                } else {
                    _Errou.Text = (++_retirar).ToString();
                }
            }
        }
    }
    

    I've improved, but there are a few more things that can be improved.

    Obviously the solution to give a generic error message is a gambiarra, put in the code the action that is most appropriate for your code. But be sure to treat the user to enter something wrong.

    As a complement to C # 7 you can write the code a bit better without having to declare the variable that will receive the value in advance:

    if (int.TrypParse(_TextValMin.Text, out var valMin)) {
        //faz algo aqui
    }
    
        
    19.05.2016 / 16:00
    1

    You can not compare two Strings as being greater or smaller, and so that the program does not give error when the user does not want to put a character other than a number, you must use NupericUpDown that limits the input to numbers and then you use like this:

    if (_TextValPalite.Value > _ValSorteado.Value)
    

    That is, instead of using the Text attribute, you use Value .

        
    19.05.2016 / 15:49
    1

    If you just want to convert your variable to an integer then you only do this:

    int.Parse(_TextValPalite)
    

    The convert.toint has a problem that can be serious sometimes, run a try catch from behind!

        
    19.05.2016 / 16:32