我正在尝试使用一个辅助方法来检查一个单词中的所有字符是否都是元音。
然后,我尝试创建另一个方法,该方法使用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";
}
}
}
在这方面的任何帮助都将非常感谢。
谢谢。
发布于 2018-10-15 06:34:43
下面是一些可以帮助你前进的事情:
仅仅从一个方法返回一个字符串并不能将其输出到任何地方。所以,替换掉
askForWords(scan);
使用
System.out.println(askForWords(scan));
在main()
中将向您显示该方法的结果。
在检查元音时,需要遍历整个单词,而不是在遇到的第一个元音处停止。使用您当前的代码,最简单的修复方法是反转return
语句的值和比较的真实值:
for (int i = 0; i < str.length(); i++) {
if ( !( // <- if the string has any other characters than the ones below, return a falsey
(str.charAt(i) == 'a')
|| (str.charAt(i) == 'e')
|| (str.charAt(i) == 'i')
|| (str.charAt(i) == 'o')
|| (str.charAt(i) == 'u'))) {
return false;
}
}
return true;
您还会遇到其他一些问题,比如代码最多只能运行两个输入字符串(您需要一个循环而不是一个if-else
),但是这些问题有点离题。
https://stackoverflow.com/questions/52807515
复制相似问题