Random button with isEmpty ();

1

Hello, I'm new to programming with Java and now a little Android. I am trying to use Random to issue random messages if nothing is typed. So, my code looks 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 tried also to use this within the action of the button instead of random :

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

When I run the program on my phone and hit the button to see if any text message is output in the "result", it gives an error and it closes.

Can anyone explain what might be wrong?

    
asked by anonymous 25.11.2016 / 16:37

2 answers

0

First, you should only create 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 it should be this:

resultadoIdade.setText(frases[numAleatorio]);
    
25.11.2016 / 16:50
0

You can try replacing:

textoDigitado.isEmpty()

by

textoDigitado.equalsIgnoreCase("")
    
25.11.2016 / 16:50