【发布时间】:2018-11-08 13:21:12
【问题描述】:
我是 java 的新手,我们班上有一个我没有的作业 很明白。
程序应将输入的单词翻译成 Pig Latin。所以每个以元音开头的单词应该显示为“word + lay”,每个以辅音开头的单词应该显示为“word_without_the_consonant_at_the_beginning + consonant + 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 +
" ");
}
}
}
【问题讨论】:
-
您能否简要解释一下代码的预期用途?
-
代码应该将输入的任何以元音开头的单词更改为单词+lay。对于每个以辅音开头的单词,代码应该将单词变成开头没有辅音的单词+辅音+ ay。
标签: java while-loop boolean