我是Java中的newby,我们在课堂上有一个作业,我没有 相当了解。
程序应将输入的单词翻译成Pig Latin。因此,每个以元音开头的单词应显示为“单词+居所”,而每个以辅音开头的单词应显示为“ word_without_the_consonant_at_the_beginning +辅音+ ay”。
我的问题是我不明白为什么需要这样做 被包括在内。有人可以向我解释吗?特别是因为我已经 在代码开头输入了这些变量。
firstVowelFound = false;
firstIndex = 0;
在这种情况下,为什么需要firstVowelFound?为什么我要包含它 在这里:
while ((firstIndex < scannedWords.length()) && !firstVowelFound)
这是由老师纠正的代码。粗体字是那些 我不明白。希望你能帮助我。谢谢!!
import java.util.Scanner;
public class PigLatin2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Scanner wordScanner;
String
wordInput = "",
scannedWords = "",
pigLatinWord = "";
int
firstIndex = 0;
char
firstLetter;
boolean
firstVowelFound = false;
while (keyboard.hasNextLine()) //as long as there is input, read input.
{
wordInput = keyboard.nextLine().toLowerCase();
wordScanner = new Scanner(wordInput);
while (wordScanner.hasNext()) //read input to find out the words
{
scannedWords = wordScanner.next();
**firstVowelFound = false;
firstIndex = 0;
//for the following part, the program looks for the first Index of
//each word. If the letters of switch are included, boolean is
//true.
while ((firstIndex < scannedWords.length()) && !firstVowelFound)**
{
firstLetter = scannedWords.charAt(firstIndex);
switch (firstLetter)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
**firstVowelFound = true;**
break;
default:
// no vowel occurred in the word, so look for more words.
firstIndex++;
}
}
/*the following parts create pigLatin Words. When index is 0, all
words starting with a vowel will be word + lay, any other word
will display word with the first letter + ay displayed at the end
of the word */
if (firstIndex == 0)
{
pigLatinWord = scannedWords + "lay";
}
else
{
pigLatinWord = scannedWords.substring(1) +
scannedWords.substring(0,1) + "ay";
}
}
System.out.println("Pig Latin for your entered word is " +
pigLatinWord +
" ");
}
}
}
答案 0 :(得分:1)
firstVowelFound
可以确保找到第一个元音时while循环中断。实际上,如果没有它,循环将是无限的。
代码中可能令人困惑的是break
中的switch
。它不会使程序退出while循环,而只会退出开关。