gpt4 book ai didi

java - 我正在尝试从字符串中删除所有元音

转载 作者:行者123 更新时间:2023-12-01 10:51:08 24 4
gpt4 key购买 nike

我是java初学者,我有这段代码,它说我需要我缺少一个返回语句:我的代码有什么问题吗?

import java.util.Scanner;
public class Excercise4 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
System.out.printf ("New string: %s", removeVowels(word));
System.out.print ("\nThank you for using the system");
}
public static String removeVowels (String word) {
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if ((c == 'A') || (c == 'a') || (c == 'E') || (c == 'e') || (c == 'I') || (c == 'i')
|| (c == 'O') || (c == 'o') || (c == 'U') || (c == 'u')) {
String front = word.substring(0, i);
String back = word.substring(i + 1);
String NewWord = front + "" + back;
return NewWord;

}
}
}
}

最佳答案

在 if 之后提供一个替代方案并返回该情况的值:

        if ((c == 'A') || (c == 'a') || (c == 'E') || (c == 'e') || (c == 'I') || (c == 'i')
|| (c == 'O') || (c == 'o') || (c == 'U') || (c == 'u')) {
String front = word.substring(0, i);
String back = word.substring(i + 1);
String NewWord = front + "" + back;
return NewWord;

}
/*HERE is where you needed the return value*/
else
return somethingElse;
}

这是一个简短的工作解决方案:

      public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
System.out.printf ("New string: %s", removeVowels(word));
System.out.print ("\nThank you for using the system");
}

public static String removeVowels (String word) {
String str=word;
str = str.replaceAll("[AEIOUaeiou]", "");
return word;
}

关于java - 我正在尝试从字符串中删除所有元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33896731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com