Generate random number in a user-given range - Java/Android

Asked

Viewed 182 times

1

I’m trying to generate a random number in a user-given range. Android Studio does not point error, however the app does not generate any value. What may be wrong? Thanks in advance!

public class MainActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView generate = findViewById(R.id.Generator);

        generate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                EditText minValue = findViewById(R.id.Min);
                EditText maxValue = findViewById(R.id.Max);
                TextView finalValue = findViewById(R.id.Value);

                String minString = String.valueOf(minValue);
                String maxString = String.valueOf(maxValue);

                int min = Integer.parseInt(minString);
                int max = Integer.parseInt(maxString);

                if (max > min) {
                    Random randGen = new Random();
                    int generate = randGen.nextInt((max - min) + 1) + min;
                    String genString = String.valueOf(generate);
                    finalValue.setText(genString);
                    }
                }
            });
        }
}

2 answers

2


Good evening, you need to recover the values passed in Edittext

instead of using:

  String minString = String.valueOf(minValue);
  String maxString = String.valueOf(maxValue);

Let:

            String minString = String.valueOf(minValue.getText());
            String maxString = String.valueOf(maxValue.getText());

Note: Instead of using a Textview as a button, why not use the same Button?

  • If my answer was helpful, please accept it as a response to the left side and if possible mark it as useful.

0

Whoa, that’s all right!?

the error is here:

String minString = String.valueOf(minValue);
String maxString = String.valueOf(maxValue);

So vc is only receiving edittext, you need to convert the object into a string using . toString(). In your case, you can already take the int directly by toString(), eliminating some lines of code.

int min = Integer.parseInt(minValue.getText.toString);
int max = Integer.parseInt(maxValue.getText.toString);

Browser other questions tagged

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