【发布时间】:2018-10-14 22:10:06
【问题描述】:
我正在尝试使用辅助方法来检查单词中的所有字符是否都是元音。
然后我尝试创建另一种方法,该方法使用 Scanner 作为参数,并不断要求用户输入一个单词,直到用户输入一个包含所有元音的单词。 (单词不一定是单词,也可以是 ieuo)。
我不知道如何让该方法验证扫描仪是所有元音,然后返回正确的输出。
这是我目前所拥有的:
import java.util.*;
public class LabFinish {
public static void main(String[] args) {
System.out.println("Enter a word: ");
Scanner scan = new Scanner(System.in);
askForWords(scan);
public static boolean isAllVowels(Scanner scan) {
String str = scan.nextLine();
for (int i = 0; i <= str.length(); i++)
if ((str.charAt(i) == 'a') ||
(str.charAt(i) == 'e') ||
(str.charAt(i) == 'i') ||
(str.charAt(i) == 'o') ||
(str.charAt(i) == 'u')) {
return true;
}
return false;
}
public static String askForWords(Scanner scan) {
if (isAllVowels(scan) == true) {
return "Finally all vowels, we are done.";
}
else {
System.out.println("Enter a word: ");
Scanner scan1 = new Scanner(System.in);
if (isAllVowels(scan1) == true) {
return "Finally all vowels, we are done.";
}
else {
return "Enter a word";
}
}
}
对此的任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
为什么不使用正则表达式?
-
因为那样他们会有两个问题?
-
不是答案,而是建议 - 始终使用
{ }字符和for循环。在您的示例中,return false;是在for循环内部还是外部并不明显。它实际上在外面,但是你的缩进让它看起来像是在里面。区别很重要。所以总是使用{ },只是为了说明清楚。