简体   繁体   中英

Select array2 item by index based on array1 random item by index

The title is pretty explanatory, I'm not sure how to make arrays where each item has items within one another, so this is what I figured out for a solution. Is to make two separate arrays so that when a random item is selected from Array1, the code will then automatically pull the item from the second array with the same Index value. This is what I have regarding code, it's not much, I'm not very experienced when it comes to this.

higher.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String[] array = getResources().getStringArray(R.array.terms);
            String[] array2 = getResources().getStringArray(R.array.url);
            String randomStr = array[new Random().nextInt(array.length)];
            text1.setText(randomStr);
            text2.setText(?????);
        }
    });

So ideally I want it to pull the value from the second array matching the Index of the first one and display it in the "text2".

Thank you in advance!

It is kind of easy. Just save that random value and use that in both arrays.

     String[] array = getResources().getStringArray(R.array.terms);
     String[] array2 = getResources().getStringArray(R.array.url);

        Random random = new Random();
        int index = random.nextInt(array.length);
            String randomStr = array[index];
            text1.setText(randomStr);
            text2.setText(array2[index]);

Do it like this :

higher.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String[] array = getResources().getStringArray(R.array.terms);
        String[] array2 = getResources().getStringArray(R.array.url);
        String randomStr = array[new Random().nextInt(array.length)];
        text1.setText(randomStr);

        // HERE i made the changes            

        int pos = Arrays.asList(array2).indexOf(randomStr);

        text2.setText(array2[pos]);
    }
});

Just given an alternative method of how to find the index of any particular element in array .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM