0

I want to get some specific number random values from 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.

2
  • Thought about using a debugger or old style 'printf debugging'? Commented Feb 16, 2013 at 19:15
  • Style note but it's a good idea to code to interfaces where possible: final List<Map<String, String>> menuItems = new ArrayList<Map<String, String>>(); Commented Feb 16, 2013 at 19:19

2 Answers 2

5

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

Explanation:

A for loop has the following structure:

for (initialization; condition; update)

initialization is executed once before the loop starts. condition is checked before each iteration of the loop and update is executed after every iteration.

Your initialization was int i = 0; (executed once). Your condition was i == 4, which is false, because i is 0. So the condition is false, and the loop is skipped.

Sign up to request clarification or add additional context in comments.

Comments

2

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).

This tutorial explains how the for statement works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.