ProfessorStealth
ProfessorStealth

Reputation: 125

Java While Loop Not Executing

I am attempting to build a simple program, and the first part of my program will not work correctly.

Could someone please check my code and tell me why the while loop will not execute and generate a proper random number?

Thank you in advance.

Upvotes: 0

Views: 145

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201527

If I understand your code and question, you wanted something like

int choice = 1;
int length = 8;
StringBuilder sb = new StringBuilder();

Random rand = new Random();
if(choice == 1) {
    //Lowercase Letters
    for(int i = 0; i < length; i++) {
        // from 'a' to ('z' - 'a')
        int randNumLower = 'a' + rand.nextInt('z'-'a');
        sb.append((char) randNumLower);
    }
}
System.out.println(sb.toString());

Which outputs a String of random lower case letters here.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160311

You probably mean this:

while ((num < 97) || (num > 122)) {
    num = randNumList.nextInt(122)+1;
}

Three outputs with length 5:

ordfg
idlxw
ugznu

Your condition should be || (or) not && (and). randNumLower cannot be both below 97 and above 122, it must be one or the other (or in-between).

To use your confusing negations, you'd need:

(!(num >= 97) || !(num <= 122))

This is harder to read, as far as I'm concerned.

Better yet, skip all that, and just use the correct range:

num = randNumList.nextInt('z' - 'a') + 'a';

Note that the optimization of using an explicit StringBuilder isn't strictly necessary since when it matters it will be used under the covers.

Upvotes: 1

Related Questions