所以我有這樣的代碼是應該產生長的隨機單詞的用戶具備這些條件決定:我如何重複的if語句,直到它在Java的假
[1] Every other letter is a random vowel (letter + vowel + letter + vowel...etc)
[2] Two vowels cannot meet together (ie: bout, caravaa)
我得到了第一部分條件,第二個條件需要一些編輯。 我用一個if語句來檢查letter1
或letter2
恰好是元音,如果是真則產生不同的字母。問題是那些新生成的字母有機會成爲元音。我如何不斷重複if語句直到它是錯誤的? (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);
}
}
}
}
明白的,如果塊不是一個循環,並在它自己的不重複。所以要回答你的問題 - 你沒有。您使用while循環和條件來重複代碼塊。 –
我如何使用while循環並在我的情況下給它條件? @HovercraftFullOfEels –
不要問 - 嘗試和測試。 –