[英]get multiple random values from ArrayList HashMap
I want to get some specific number random values from ArrayList 我想从ArrayList获取一些特定的数字随机值
final ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
for (int i = 0; i == 4; i++) {
index = random.nextInt(menuItems.size());
HashMap<String, String> getitem = menuItems.get(index);
System.out.println(getitem.get(KEY_NAME));
}
Nothing is printing out. 什么都没打印出来。
Code in loop works if i use it outside loop, but since i need multiple values, i use loop and it doesnt work. 如果我在循环外使用它,则循环中的代码可以工作,但是由于我需要多个值,因此我使用循环,但它不起作用。
change 更改
for (int i = 0; i == 4; i++) { // start with i beeing 0, execute while i is 4
// never true
to 至
for (int i = 0; i < 4; i++) { // start with i beeing 0, execute while i is
// smaller than 4, true 4 times
A for loop has the following structure: for循环具有以下结构:
for (initialization; condition; update)
initialization
is executed once before the loop starts. initialization
在循环开始之前执行一次。 condition
is checked before each iteration of the loop and update
is executed after every iteration. 在循环的每次迭代之前检查condition
并在每次迭代之后执行update
。
Your initialization was int i = 0;
您的初始化是int i = 0;
(executed once). (执行一次)。 Your condition was i == 4
, which is false, because i
is 0
. 您的条件是i == 4
,这是错误的,因为i
为0
。 So the condition is false, and the loop is skipped. 因此条件为假,并且跳过了循环。
The ending condition of your for loop is broken: for (int i = 0; i == 4; i++)
should be for (int i = 0; i < 4; i++)
(4 iterations) or for (int i = 0; i <= 4; i++)
(5 iterations). for循环的结束条件被破坏: for (int i = 0; i == 4; i++)
应该是for (int i = 0; i < 4; i++)
(4个迭代)或for (int i = 0; i <= 4; i++)
(5次迭代)。
This tutorial explains how the for
statement works. 本教程说明了for
语句的工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.