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

标签 java

我是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/

相关文章:

java - 如何确保将特定参数传递给方法?

java - 计算 Java 中的实例

java - 为什么我不能使用 LinkedList::new?

java - 如何更改 TTS 引擎的声音

java - 从哪里获得 com.sun.j3d 类

Java RMI 通过互联网

java - 从列表末尾迭代

JavaFX GridPane 列/行跨度与索引

java - 将 Java 字节码翻译成其他表示和编程语言

java - 如何使用 xtend 设置 java 注释的多个属性(使用 xbase)