Array of phrases in Java

Asked

Viewed 659 times

0

I’m studying Java, and Android development, and I want to make this application to understand how it works.

I’m using the Toast class so that when I click on the image, a sentence appears, I can make it work with numbers, but instead I want to put some sentences and when I click on the image, the phrase appears for a few seconds on the screen.

How do I do this without many changes in this code I already have?

    package android.tutorial.android;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

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

// public void mostrarMensagem(View view) {
    //Toast toast = Toast.makeText(this.sorteia(), Toast.LENGTH_SHORT);
    //toast.show();

  //}


 public void mostrarMensagem(View view) {
     int[] lista = new int[]
             {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
             };
     StringBuilder builder = new StringBuilder();
     for(int i : lista)
     {
          builder.append("" + i + " ");
     }
     Toast.makeText(this, builder, Toast.LENGTH_LONG).show();


      }


}

Array com Toast

  • 1

    I don’t understand why array of phrases, because if you want to display only one sentence just change the variable builder within the Toast by a string. That’s it?

  • @Paulorodrigues What I want is for each click to appear a different message!

  • @Paulorodrigues with this code below, if I register 5 messages in the array and give a single tap on the screen will appear the 5 mesnagens, one after the other and that’s not what I want. 1 tap, 1 message. String [] arr = new String []{"sentence one", "sentence two"}; for(String str : arr) Toast.makeText(this, str, Toast.LENGTH_LONG). show(); }

1 answer

1


Do something like this:

public void mostrarMensagem(View view) {
    String[] lista = new String []{"sentence one", "sentence two"};
    String randomStr = lista[new Random().nextInt(lista.length)];

    Toast.makeText(this, randomStr, Toast.LENGTH_LONG).show();
}

Remembering that there is no rule of not being able to repeat the phrase, for that would have to do something more.

  • For now it was just what I wanted, will serve me as a basis of studies, I will understand these codes there. If it’s not too much, can you give me the path of stones to avoid repetition of sentences? Thanks a lot for the help!

Browser other questions tagged

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