0

I hope you can help me.

I make a game like 4Pics1Word.

I want to load the Level Randomly, I want a loop which generate a Random number from 0 to 10, and then check if the generated number is the first time loaded. If yes write it in an array and end the loop. If the number is not the first time loaded, generate a new random number and check it again until it is not used.

For example this is my code (don´t work right):

Boolean usedImageSet = false;
    for (int t = 0; t <= usedImages.length; t++) {
        if (usedImageSet == false) {
            StringBuilder sb = new StringBuilder();
            sb.append(currentQuestion);
            String used = sb.toString();            

            if (usedImages[t] != null) {
                System.out.println("usedImage" + t
                        + " = not Null, it is" + usedImages[t]);
                if (usedImages[t].equals(used)) {
                    System.out.println("String: "
                            + used
                            + " found it here: [" + t + "]");
                    currentQuestion = (int) (Math.random() * 10);

                }else {
                    System.out.println("String: "
                            + used + " not found");
                }
            }
            if (usedImages[t] == null) {
                usedImages[t] = used;
                System.out.println("useddImage[" + t + "]: "
                        + usedImages[t]);
                System.out.println("usedImage" + t + " is Null, change to"
                        + usedImages[t]);
                usedImageSet = true;
            }
        }

    }

PS: Thank you all, I think the solution from Oren is the best

    // naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
    list.add(i);
}
Collections.shuffle(list);

// output the generated list
for(int i=0; i<10; i++)
{
    System.out.print(list.get(i));
}

But how can I save the list if I close the game?

0

2 Answers 2

2

You would probably be much better off creating a List of the numbers you want and then calling Collections.shuffle() on that list.

// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
    list.add(i);
}
Collections.shuffle(list);

// output the generated list
for(int i=0; i<10; i++)
{
    System.out.print(list.get(i));
}
Sign up to request clarification or add additional context in comments.

Comments

0
    int oldnumber = 5;
    int newnumber = new Random().nextInt(10);
    while (newnumber == oldnumber){
        newnumber = new Random().nextInt(10);
    }

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.