Jawny Thompson Jawny Thompson - 1 month ago 6
Java Question

How do i repeat an if statement until it's false in Java

So i have this code that is supposed to generate random words of length the user decides with these conditions:

[1] Every other letter is a random vowel (letter + vowel + letter + vowel...etc)
[2] Two vowels cannot meet together (ie: bout, caravaa)


I got over the first part condition, and the second condition needs some edit.
i used an if statement to check if
letter1
or
letter2
happen to be vowels, and if true generate generate different letters. Problem is those newly generated letters have a chance of being vowels. How do i keep repeating the if statement until it's false?
(Letter1 and Letter2 are not vowels)


import java.util.Random;

public class NickName_1
{
public static void main(String[] args)
{
java.util.Scanner scanner = new java.util.Scanner(System.in);

int letterNum = 6;
Random rn = new Random();
char letter1 = (char) (rn.nextInt(26) + 'a');
char letter2 = (char) (rn.nextInt(26) + 'a');
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
char vowel;


while (true)
{
//Ask user for word's length and store it
System.out.println();
System.out.print("Please enter the length of the word in letters: ");
letterNum = scanner.nextInt();

vowel = vowels[(int)(Math.random() * 5)];

for (int i = 0; i < (letterNum / 3); i++)
{
letter1 = (char) (rn.nextInt(26) + 'a');
letter2 = (char) (rn.nextInt(26) + 'a');
vowel = vowels[(int)(Math.random() * 5)];

// if letter1 or letter2 equal a vowel then regenerate letters
if (letter1 == 'a' || letter1 == 'u' || letter1 == 'i' || letter1 == 'e' || letter1 == 'o' ||
letter2 == 'a' || letter2 == 'u' || letter2 == 'i' || letter2 == 'e' || letter2 == 'o')

{
letter1 = (char) (rn.nextInt(26) + 'a');
letter2 = (char) (rn.nextInt(26) + 'a');
}
System.out.print(letter1 + "" + vowel + "" + letter2);
}
}
}
}

Answer

Just replace your if statement with a while statement.

while (letter1 == 'a' || letter1 == 'u' || letter1 == 'i' || letter1 == 'e' || letter1 == 'o' || 
       letter2 == 'a' || letter2 == 'u' || letter2 == 'i' || letter2 == 'e' || letter2 == 'o')
{
    letter1 = (char) (rn.nextInt(26) + 'a');
    letter2 = (char) (rn.nextInt(26) + 'a');
} 

Update:

Looking at your code, it would be much better to check each of the letters separately, otherwise letter1 could be getting consonants but because letter 2 is not it continues changing both of them.

while (letter1 == 'a' || letter1 == 'u' || letter1 == 'i' || letter1 == 'e' || letter1 == 'o')
{
    letter1 = (char) (rn.nextInt(26) + 'a');
}
while (letter2 == 'a' || letter2 == 'u' || letter2 == 'i' || letter2 == 'e' || letter2 == 'o')
{
    letter2 = (char) (rn.nextInt(26) + 'a');
}
Comments