Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从数组中随机选择字符串并设置为textview_Java_Android Studio - Fatal编程技术网

Java 如何从数组中随机选择字符串并设置为textview

Java 如何从数组中随机选择字符串并设置为textview,java,android-studio,Java,Android Studio,我在res/values文件夹中创建了array.xml,其中包含5个字符串(avalaible_bus作为数组的名称)。请告诉我如何从这个数组中随机选择字符串并显示在textview上。下面是我的尝试。seatNumber是文本视图的名称 public void seatNumber (View view) { String[] myArray = getResources().getStringArray(array.avalaible_buses); TextView

我在res/values文件夹中创建了array.xml,其中包含5个字符串(avalaible_bus作为数组的名称)。请告诉我如何从这个数组中随机选择字符串并显示在textview上。下面是我的尝试。seatNumber是文本视图的名称

public void seatNumber (View view) {     
String[] myArray = getResources().getStringArray(array.avalaible_buses);     
TextView seatNumber = (TextView) findViewById(R.id.seatNumber);     
Random random = new Random();     
seatNumber.setText(random.nextInt(myArray)); 
}

把问题分成几个小部分

生成一个介于0和数组最后一个索引之间的随机数

// get a random number between 0 and array length - 1 inclusive (last index)
Random random = new Random();     
int index = random.nextInt(myArray.length);
更新用户界面

seatNumber.setText(myArray[index]);
注意

数组定义为

String[] myArray = getResources().getStringArray(array.avalaible_buses);
从编写的方式来看,阵列资源(
可用_总线
)处理的是实际总线,而不是总线上的座位。如果这是正确的,我希望有一个文本(ui)控件,如
busName

如果您要为乘客分配一个随机数(座位号),您还需要跟踪谁上谁下,以避免将相同的随机数分配给两个人。换句话说,阵列会根据可用性进行更改。

更改行5,如下所示

public void seatNumber (View view) {     
    String[] myArray = getResources().getStringArray(array.avalaible_buses);     
    TextView seatNumber = (TextView) findViewById(R.id.seatNumber);     
    Random random = new Random();     
    seatNumber.setText(myArray(random.nextInt(myArray.length)));  // Line #5
}

获取一个随机索引。在0和array.length之间选择->数字-1是您的索引