简体   繁体   中英

Using string-array list length as an integer

I'm using a random number generator to select an item out of an Android string array. Is there a way to set my integer as the length of the array without actually counting the number of items in the array?

Here's an example of the random number code I'm using:

private Random random = new Random();
private int n = random.nextInt(4);

private String randText;

public Object(Context contex)
{
String[] string = context.getResources().getStringArray(R.array.text);

randText = "Stuff to display " + string[n] +".";
}

public String getRandText
{
return randText
}

I would like to define the "4" above as the length of a specific array list. Anyone know how?

List myList = ...
int n = select.nextInt(myList.size());

I would like to define the "4" above as the length of a specific array list.

Perhaps this is what you're after:

String[] strs = { "str1", "str2", "str3", "str4", "str5" };

// Select a random (valid) index of the array strs
Random rnd = new Random();
int index = rnd.nextInt(strs.length);

// Print the randomly selected string
System.out.println(strs[index]);

To access the actual array, you do the following:

Resources res = getResources();
String[] yourStrings = res.getStringArray(R.array.your_array);

(Then to get the number of elements in the array, you do yourStrings.length .)


Regarding your edit. Try this instead:

private Random random = new Random();
private int n; // Can't decide up here, since array is not declared / initialized

private String randText;

public YourObject(Context contex) {
    String[] string = context.getResources().getStringArray(R.array.text);
    n = random.nextInt(string.length);     // <--- Do it here instead.
    randText = "Stuff to display " + string[n] +".";
}

public String getRandText {
    return randText;
}

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