0

I'm trying to make a simple game where the sentence will be shuffled but I want to split it with each word. How can I loop my string value word by word just like in this Sample Image.

public class MainActivity extends AppCompatActivity {

    TextView textview1, textview2;
    CardView text1;

    //Initializing string variable.
    String value = "Testing to shuffle an array" ;

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

        textview1 = findViewById(R.id.textView1);
        textview2 = findViewById(R.id.textView2);
        text1= findViewById(R.id.txt1);

        //Converting string variable to byte array.
        String[] words=value.split(" ");
        //printing string on screen.
        textview1.setText("String = " + value);
        //Printing array on screen.
        textview2.setText("Shuffled = ");

        Random r = new Random();
        for (int i = words.length-1; i >= 0; i--) {
            // Pick a random index from 0 to i
            int j = r.nextInt(i+1);
            // Swap words[i] with the element at random index
            String temp = words[i];
            words[i] = words[j];
            words[j] = temp;
            textview2.setText(textview2.getText() +""+ words[i]+" ");
        }
    }
}
Kazz Domi
  • 17
  • 1
  • 5

1 Answers1

0

This may not answer your question completely but here's a concise approach to "shuffling" the word list:

public static void main(String[] args) {
    String value = "Testing to shuffle an array" ;
    String[] words=value.split(" ");
    List<String> wordList = Arrays.asList(words);
    Collections.shuffle(wordList);
    System.out.println(wordList);
}

which prints as an example

shuffle array Testing to an

If you wanted to display in the one textview as you are currently doing (delimited by space):

textview2.setText(textview2.getText().toString() + String.join(" ",wordList));

As for using multiple TextViews that would require seeing your layout for a starting point. Since you may be dealing with a variable number of words you would need to programmatically add the views - one for each word.

Here's an example of that.

Computable
  • 976
  • 2
  • 4
  • 16