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

时间:2015-11-24 14:51:01

标签: java

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

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;

            }
            }
    }
}

3 个答案:

答案 0 :(得分:1)

在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;
        }

答案 1 :(得分:0)

可能永远不会访问

if分支(如果您的单词中没有任何元音),那么您应该添加else分支

此外,您的代码将无效,因为您只删除了第一个元音

答案 2 :(得分:0)

word.replaceAll("[AEIOUaeiou]", "")怎么样?

<强>用法:

public class RemoveVowels {

    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", word.replaceAll("[AEIOUaeiou]", ""));
        System.out.print("\nThank you for using the system");
        keyboard.close();
    }
}