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

Asked

Viewed 160 times

11

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 values (!=) I can, but for higher values (>) or lower values (<) no, it returns the following error:

Operator '>' cannot be Applied to operands of type 'string' and 'string'

SS

  • 2

    How about converting to int?

  • I have made a gist to improve your code a little and solve your problem as well. Take a look, it can help to learn a few things. https://gist.github.com/brunoss/e960713775b4c35ef8f760c10bd0abe6

  • Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to do this. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

4 answers

6

Obs.: My answer takes into account that the data entered by the user will be validated separately (maybe in the method Leave of the component, or something similar) and that in no case it will be possible to make the conversion methods receive invalid values. If you are unsure of the integrity of values, give preference to the use of TryParse as in @Maniero’s reply.

You can’t even do this kind of comparison with strings.

You need to convert types to number.

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

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

use:

if(valorPalpite < valorSorteado) { ... }

I would save the variables at the very beginning of the click event and then use them to do all necessary validations and/or calculations.

If you prefer, you can do the conversion when checking

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

Additional:

  1. Convert.ToInt32 is not the only way to convert a string for number, for more details you can see the answers in What is the main difference between int. Parse() and Convert.Toint32()?
  2. The name of the variables are not following the C nomenclature standard#. The only ones who are following the pattern are _adicionar and _retirar, the rest should not have underscore (_).

6

The real problem throughout this code is that it is not handling the text data well. Something similar to what happens in the answer placed on another question.

If you want to insist on using text the correct is to use the method Compare(). But I wouldn’t advise.

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

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 put in the Github for future reference.

I gave an improved, but still have a few more things that this code can be improved.

Obviously, the solution to give a generic error message is a gambiarra, put in the code the action that is most suitable for your code. But be sure to address the possibility of the user entering something wrong.

As a complement in C# 7 it is possible to write the code a little 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
}

1

You cannot compare two Strings as being larger or smaller, and in order for the program to fail when the user doesn’t want to put a character other than a number, you should use NupericUpDown which limits the input to numbers and then uses it like this:

if (_TextValPalite.Value > _ValSorteado.Value)

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

1

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

int.Parse(_TextValPalite)

Convert.toint has a problem that can be severe sometimes, runs a Try catch from behind!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.