有 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;

            }
            }
    }
}

共 (3) 个答案

  1. # 1 楼答案

    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();
        }
    }
    
  2. # 2 楼答案

    在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;
            }
    
  3. # 3 楼答案

    if分支可能永远不会被访问(如果您的单词中没有任何元音),因此您应该添加else分支

    此外,您的代码将无法工作,因为您只删除第一个元音