Random on button with isEmpty();

Asked

Viewed 50 times

1

Hello, I’m new in programming to studying Java and now some Android. I’m trying to use the Random to send random messages if nothing is typed. So, my code is like this:

public class MainActivity extends AppCompatActivity {

private EditText caixaTexto;
private Button botaoIdade;
private TextView resultadoIdade;
private String[] frases = {"Digite um número", "Digita logo o número", "Cara, digita logo isso"};


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

    caixaTexto = (EditText) findViewById(R.id.caixaTextoId);
    botaoIdade = (Button) findViewById(R.id.botaoIdadeId);
    resultadoIdade = (TextView) findViewById(R.id.resultadoIdadeId);

    botaoIdade.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //recuperar o que foi digitado
            String textoDigitado = caixaTexto.getText().toString();

            if(textoDigitado.isEmpty()){
                Random random = new Random();
                int numAleatorio = random.nextInt(frases.length);
                //String vazia receberá uma mensagem de erro
                resultadoIdade.setText(numAleatorio);

            }else{
                int valorDigitado = Integer.parseInt(textoDigitado);
                int resultadoFinal = valorDigitado * 7;

                resultadoIdade.setText("A idade do cachorro em anos humanos são: " +
                        resultadoFinal + " anos.");
            }
        }
    });

I also tried to use this inside the button action instead of the random:

Toast.makeText(getApplicationContext(), "Mensagem", Toast.LENGTH_LONG).show();

When I run the program on my mobile and press the button to see if any message comes out in Textview "result", gives error and it closes.

Can anyone explain what might be wrong?

2 answers

0

You can try to replace:

textoDigitado.isEmpty()

for

textoDigitado.equalsIgnoreCase("")

0


First, you should just create the Random once and then reuse it:

private static final Random random = new Random();

Second, this line should not do what you want:

resultadoIdade.setText(numAleatorio);

I think that should be it:

resultadoIdade.setText(frases[numAleatorio]);
  • It worked, thanks. I just didn’t understand why it didn’t work, because I played the array.length inside the textDigited...Thanks anyway

  • @Andrésantos If this answer has served you, you will not forget to mark it as correct/accepted by clicking on the green side of the answer. It turns out that numAleatorio and array.length are of the type int, whereas frases[numAleatorio] and textoDigitado are of the type String.

Browser other questions tagged

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