Search code examples
javaif-statementrandom

How to nest if/then/else statements into random list outputs?


I'm trying to create a system that picks randomly from a list, and then, depending on which string it picked, picks another random string from a separate group, and then another one from there.

Basically, I'm trying to give it a bunch of paths and then, depending on what choice it makes, narrow the subsequent paths down two more times.

I've got the random code going, but I can't get it to accept if/then/else statements.

Here is my code. It works for its current purpose, which is generating one of those 4 letters randomly. But because it doesn't call a variable, it won't accept if/then/else statements. If I try to make a variable, it complains about being unable to convert the variable to Boolean, but if I define it as Boolean the entire code breaks.

package randomlist;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Randomlist {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Random generate = new Random();
        String[] name = {"A", "B", "C", "D"};
        System.out.println(name[generate.nextInt(4)]);
        String nesting = (name[generate.nextInt(4)]);
        if (nesting = "A") {
            Random generate = new Random();
            String[] name = {"E", "F", "G", "H"};
        }
        else if (nesting = "B") {
            Random generate = new Random();
            String[] name = {"I", "J", "K", "L"};
        }
    }
}

EDIT: Seems nobody is able to be helpful without also being needlessly sarcastic and demeaning. Apparently, it's not okay for people to learn how to do things and everyone is expected to be an expert from the beginning. (Also, if the code compiles, it works. It might not work as intended, but it works. I do not understand the point of arguing with someone about that. Do not tell me my code won't function when I have tested it and it does, in fact, compile without errors).

Fortunately, I solved my own problem, mostly out of spite. It requires new variables every time and a lot of very short if statements, but it does what I need it to do.

Edit #2: it turns out it's willing to reuse the same variables for each nested level, so while it won't let me reuse (name) for the lower level, I can use (name1) for each of the lower nests and (name2) for the third-order ones.


Solution

  • You better should start with some Java lessons:

    • The =-operator in any case will assign the right value to the variable on the left side.
    • For comparison of two primitive types (int, double) you have to use the ==-operator. But since string are objects you'll have to use the equals-method: "A".equals(nesting).